package com.bio.bio_backend.global.security;

import java.io.IOException;
import java.util.Objects;

import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import com.fasterxml.jackson.databind.ObjectMapper;

import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.bio.bio_backend.global.dto.ApiResponseDto;
import com.bio.bio_backend.domain.user.member.service.MemberService;
import com.bio.bio_backend.global.constants.ApiResponseCode;
import com.bio.bio_backend.global.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@RequiredArgsConstructor
@Slf4j
public class JwtTokenFilter extends OncePerRequestFilter {

    private final JwtUtils jwtUtils;
    private final MemberService memberService;
    private final Environment env;

    private final UriAllowFilter uriAllowFilter;
    
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
    	return uriAllowFilter.authExceptionAllow(request);
    }

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

        String accessToken = jwtUtils.extractAccessJwtFromRequest(request);
        String refreshToken = jwtUtils.extractRefreshJwtFromCookie(request);

        if(accessToken == null){
            sendJsonResponse(response, ApiResponseDto.fail(ApiResponseCode.JWT_TOKEN_NULL, null));
            return;
        }

        try {
            // 토큰 유효성 검사
            try {
                if (jwtUtils.validateAccessToken(accessToken)) {
                    String username = jwtUtils.extractUsername(accessToken);
                    UserDetails userDetails = memberService.loadUserByUsername(username);

                    if (userDetails != null) {
                        UsernamePasswordAuthenticationToken authentication =
                                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        filterChain.doFilter(request, response);
                        return;
                    }
                }
            } catch (ExpiredJwtException ignored) {
                // Access Token이 만료된 경우에만 ignored >> Refresh Token 검증 수행
            }
            // Refresh Token 유효성 검사
            if (refreshToken != null && jwtUtils.validateRefreshToken(refreshToken)) {
                String username = jwtUtils.extractUsername(refreshToken);
                String role = (String) jwtUtils.extractAllClaims(refreshToken).get("role");
                String newAccessToken = jwtUtils.generateToken(username, role,
                        Long.parseLong(Objects.requireNonNull(env.getProperty("token.expiration_time_access"))));
                // 새로운 Access Token을 응답 헤더에 설정
                response.setHeader("Authorization", "Bearer " + newAccessToken);
                filterChain.doFilter(request, response);
            } else {
                sendJsonResponse(response, ApiResponseDto.fail(ApiResponseCode.ALL_TOKEN_INVALID, null));
            }
        } catch (Exception e) {
            request.setAttribute("exception", e);
        }

        filterChain.doFilter(request, response);
    }

    private void sendJsonResponse(HttpServletResponse response, ApiResponseDto<?> apiResponse) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        response.setStatus(apiResponse.getCode());

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(apiResponse);
        response.getWriter().write(jsonResponse);
    }
}
