package com.petshop.backend.security;

import com.petshop.backend.exception.ApiErrorResponder;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private static final Logger log = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);

    private final ApiErrorResponder apiErrorResponder;

    public RestAuthenticationEntryPoint(ApiErrorResponder apiErrorResponder) {
        this.apiErrorResponder = apiErrorResponder;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.warn("Unauthorized request: {} {} - {}", request.getMethod(), request.getRequestURI(), authException.getMessage());
        apiErrorResponder.write(
                response,
                HttpStatus.UNAUTHORIZED,
                "Authentication required",
                authException.getClass().getSimpleName() + ": " + authException.getMessage(),
                request.getRequestURI()
        );
    }
}
