package com.vibevault.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;

/**
 * 全局异常处理器
 * 
 * 需要实现：
 * - 捕获 ResourceNotFoundException 并返回 404 状态码
 * - 捕获 UnauthorizedException 并返回 403 状态码
 * - 捕获 ResponseStatusException 并返回对应状态码
 * - [Advanced] 统一处理其他异常，返回合适的错误响应格式
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 ResourceNotFoundException 异常
     * @param ex 异常对象
     * @return 包含错误信息的 ResponseEntity
     */
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleResourceNotFoundException(ResourceNotFoundException ex) {
        return buildErrorResponse(HttpStatus.NOT_FOUND.value(), "Not Found", ex.getMessage());
    }

    /**
     * 处理 UnauthorizedAccessException 异常
     * @param ex 异常对象
     * @return 包含错误信息的 ResponseEntity
     */
    @ExceptionHandler(UnauthorizedAccessException.class)
    public ResponseEntity<ErrorResponse> handleUnauthorizedAccessException(UnauthorizedAccessException ex) {
        return buildErrorResponse(HttpStatus.FORBIDDEN.value(), "Forbidden", ex.getMessage());
    }
    
    /**
     * 处理 UnauthorizedException 异常
     * @param ex 异常对象
     * @return 包含错误信息的 ResponseEntity
     */
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity<ErrorResponse> handleUnauthorizedException(UnauthorizedException ex) {
        return buildErrorResponse(HttpStatus.FORBIDDEN.value(), "Forbidden", ex.getMessage());
    }

    /**
     * 处理 ResponseStatusException 异常
     * @param ex 异常对象
     * @return 包含错误信息的 ResponseEntity
     */
    @ExceptionHandler(ResponseStatusException.class)
    public ResponseEntity<ErrorResponse> handleResponseStatusException(ResponseStatusException ex) {
        return buildErrorResponse(ex.getStatusCode().value(), ex.getStatusCode().toString(), ex.getMessage());
    }

    /**
     * 处理所有其他未捕获的异常
     * @param ex 异常对象
     * @return 包含错误信息的 ResponseEntity
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) {
        return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "Internal Server Error", "An unexpected error occurred");
    }
    
    /**
     * 构建统一的错误响应格式
     * @param status 响应状态码
     * @param error 错误类型
     * @param message 错误消息
     * @return 包含错误信息的 ResponseEntity
     */
    private ResponseEntity<ErrorResponse> buildErrorResponse(int statusCode, String error, String message) {
        ErrorResponse errorResponse = new ErrorResponse(statusCode, error, message);
        return ResponseEntity.status(statusCode).body(errorResponse);
    }
}
