package gc.mda.kcg.common.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * 전역 예외 처리.
 * - IllegalArgumentException → 400
 * - AccessDeniedException → 403
 * - AuthenticationCredentialsNotFoundException → 401
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    public ResponseEntity<Map<String, Object>> handleIllegal(IllegalArgumentException e) {
        log.debug("400 Bad Request: {}", e.getMessage());
        return ResponseEntity.badRequest().body(Map.of(
                "error", "BAD_REQUEST",
                "message", e.getMessage() == null ? "" : e.getMessage()
        ));
    }

    @ExceptionHandler(IllegalStateException.class)
    public ResponseEntity<Map<String, Object>> handleIllegalState(IllegalStateException e) {
        log.debug("409 Conflict: {}", e.getMessage());
        return ResponseEntity.status(409).body(Map.of(
                "error", "CONFLICT",
                "message", e.getMessage() == null ? "" : e.getMessage()
        ));
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<Map<String, Object>> handleAccessDenied(AccessDeniedException e) {
        return ResponseEntity.status(403).body(Map.of(
                "error", "FORBIDDEN",
                "message", e.getMessage() == null ? "" : e.getMessage()
        ));
    }

    @ExceptionHandler(AuthenticationCredentialsNotFoundException.class)
    public ResponseEntity<Map<String, Object>> handleNoAuth(AuthenticationCredentialsNotFoundException e) {
        return ResponseEntity.status(401).body(Map.of(
                "error", "UNAUTHENTICATED",
                "message", e.getMessage() == null ? "" : e.getMessage()
        ));
    }
}
