package com.petshop.backend.security;

import com.petshop.backend.entity.User;
import com.petshop.backend.exception.ApiErrorResponder;
import com.petshop.backend.repository.UserRepository;
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;
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserRepository userRepository;
    private final ApiErrorResponder apiErrorResponder;

    public JwtAuthenticationFilter(JwtUtil jwtUtil, UserRepository userRepository, ApiErrorResponder apiErrorResponder) {
        this.jwtUtil = jwtUtil;
        this.userRepository = userRepository;
        this.apiErrorResponder = apiErrorResponder;
    }

    @Override
    protected void doFilterInternal(
            @NonNull HttpServletRequest request,
            @NonNull HttpServletResponse response,
            @NonNull FilterChain filterChain
    ) throws ServletException, IOException {
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        jwt = authHeader.substring(7);
        Long userId;
        try {
            userId = jwtUtil.extractUserId(jwt);
        } catch (JwtException | IllegalArgumentException ex) {
            writeUnauthorized(request, response, "Invalid or expired token", ex);
            return;
        }

        if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            User user = userRepository.findById(userId).orElse(null);
            if (user == null || user.getActive() == null || !user.getActive()) {
                writeUnauthorized(request, response, "User account is inactive", null);
                return;
            }
            if (!jwtUtil.validateToken(jwt, user)) {
                writeUnauthorized(request, response, "Invalid or expired token", null);
                return;
            }

            AppPrincipal principal = new AppPrincipal(
                    user.getId(),
                    user.getUsername(),
                    user.getRole(),
                    user.getTokenVersion()
            );
            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());
    }
}
