package com.expensetracker.api.security.filter;

import com.expensetracker.api.security.service.JwtService;
import com.expensetracker.api.user.model.User;
import com.expensetracker.api.user.repository.UserRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import lombok.RequiredArgsConstructor;
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;

@Component
@RequiredArgsConstructor
public class JwtAuthFilter extends OncePerRequestFilter {

  private final JwtService jwtService;
  private final UserRepository users;

  @Override
  protected void doFilterInternal(
      HttpServletRequest request,
      HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {

    String authHeader = request.getHeader("Authorization");
    if (authHeader == null || !authHeader.startsWith("Bearer ")) {
      filterChain.doFilter(request, response);
      return;
    }

    String token = authHeader.substring(7);

    try {
      String subject = jwtService.validateAccessToken(token);

      if (SecurityContextHolder.getContext().getAuthentication() == null) {
        String principalUserId;
        if (subject.chars().allMatch(Character::isDigit)) {
          // New format: subject already contains the user id.
          principalUserId = subject;
        } else {
          // Backward compatibility: old tokens used email as subject.
          User user = users.findByEmail(subject.toLowerCase().trim()).orElseThrow();
          principalUserId = String.valueOf(user.getId());
        }

        UsernamePasswordAuthenticationToken authentication =
          new UsernamePasswordAuthenticationToken(principalUserId, null, List.of());

        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
      }
    } catch (Exception e) {
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      response.setContentType("text/plain");
      response.getWriter().write("Invalid or expired token");
      return;
    }

    filterChain.doFilter(request, response);
  }
}
