/*
 * Filter that runs on every request to validate the JWT token
 * and set up the security context if the token is valid.
 *
 * Author: Harkamal
 * Date: April 2026
 */
package com.petshop.backend.security;

import com.petshop.backend.entity.User;
import com.petshop.backend.exception.ApiErrorResponder;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Date;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserAuthCacheService userAuthCacheService;
    private final ApiErrorResponder apiErrorResponder;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserAuthCacheService userAuthCacheService, ApiErrorResponder apiErrorResponder) {
        this.jwtUtil = jwtUtil;
        this.userAuthCacheService = userAuthCacheService;
        this.apiErrorResponder = apiErrorResponder;
    }

    /**
     * Extracts the JWT from the Authorization header, validates it, and sets up
     * the Spring Security context so downstream filters/controllers know who the user is.
     * @param request the incoming HTTP request
     * @param response the HTTP response (used to write 401 errors)
     * @param filterChain the remaining filters to invoke
     */
    @Override
    protected void doFilterInternal(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain
    ) throws ServletException, IOException {
        // Skip requests that don't have a Bearer token
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        // Strip "Bearer " prefix to get the raw token
        jwt = authHeader.substring(7);
        Long userId;
        String username;
        String roleStr;
        Integer jwtTokenVersion;
        try {
            userId = jwtUtil.extractUserId(jwt);
            username = jwtUtil.extractUsername(jwt);
            roleStr = jwtUtil.extractRole(jwt);
            jwtTokenVersion = jwtUtil.extractTokenVersion(jwt);
        } catch (JwtException | IllegalArgumentException ex) {
            writeUnauthorized(request, response, "Invalid or expired token", ex);
            return;
        }

        // Only set up auth context if there isn't one already for this request
        if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            if (jwtUtil.extractExpiration(jwt).before(new Date())) {
                writeUnauthorized(request, response, "Invalid or expired token", null);
                return;
            }

            UserAuthCacheService.UserAuthData authData = userAuthCacheService.loadAuthData(userId);
            if (authData == null || !Boolean.TRUE.equals(authData.active())) {
                writeUnauthorized(request, response, "User account is inactive", null);
                return;
            }
            // Token version mismatch means the user logged out or changed password
            if (!authData.tokenVersion().equals(jwtTokenVersion)) {
                writeUnauthorized(request, response, "Invalid or expired token", null);
                return;
            }

            User.Role role;
            try {
                role = User.Role.valueOf(roleStr);
            } catch (IllegalArgumentException ex) {
                writeUnauthorized(request, response, "Invalid or expired token", ex);
                return;
            }

            // Build the authentication object and store it in the security context
            AppPrincipal principal = new AppPrincipal(userId, username, role, jwtTokenVersion);
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                    principal,
                    null,
                    principal.getAuthorities()
            );
            authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authToken);
        }
        filterChain.doFilter(request, response);
    }

    private void writeUnauthorized(HttpServletRequest request, HttpServletResponse response, String message, Exception ex) throws IOException {
        String details = ex == null ? message : ex.getClass().getSimpleName() + ": " + ex.getMessage();
        apiErrorResponder.write(response, org.springframework.http.HttpStatus.UNAUTHORIZED, message, details, request.getRequestURI());
    }
}
