package com.spring.infra.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;

import com.spring.infra.security.config.PermittedURI;

import lombok.RequiredArgsConstructor;

/**
 * JWT 인증에서 인증되지 않은 접근을 처리하는 진입점 클래스입니다.
 * 
 * @author mindol
 * @version 1.0
 */
@Component
@RequiredArgsConstructor
public class SecurityAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private static final String EXCEPTION_ATTRIBUTE = "exception";

    @Qualifier("handlerExceptionResolver")
    private final HandlerExceptionResolver resolver;
    private final HttpRequestEndpointChecker endpointChecker;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        if (!endpointChecker.isEndpointExist(request)) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else if (isApiRequest(request)) {
            handleApiRequest(request, response, authException);
        } else {
            response.sendRedirect(PermittedURI.ROOT_URI.getUri());
        }
    }

    private boolean isApiRequest(HttpServletRequest request) {
        String accept = request.getHeader(HttpHeaders.ACCEPT);
        return accept != null && accept.contains(MediaType.APPLICATION_JSON_VALUE);
    }

    private void handleApiRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        if (request.getAttribute(EXCEPTION_ATTRIBUTE) != null) {
            resolver.resolveException(request, response, null, (Exception) request.getAttribute(EXCEPTION_ATTRIBUTE));
        } else {
            resolver.resolveException(request, response, null, authException);
        }
    }
    
}
