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.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@Component
public class RestAccessDeniedHandler implements AccessDeniedHandler {

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

    private final ApiErrorResponder apiErrorResponder;

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

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.warn("Access denied: {} {} - {}", request.getMethod(), request.getRequestURI(), accessDeniedException.getMessage());
        apiErrorResponder.write(
                response,
                HttpStatus.FORBIDDEN,
                "Access Denied",
                accessDeniedException.getClass().getSimpleName() + ": " + accessDeniedException.getMessage(),
                request.getRequestURI()
        );
    }
}
