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

@Component
public class RestAccessDeniedHandler implements AccessDeniedHandler {

    private final ApiErrorResponder apiErrorResponder;

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

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