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 java.io.IOException;

@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private final ApiErrorResponder apiErrorResponder;

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

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