package org.brapi.test.BrAPITestServer.system.exception;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.brapi.test.BrAPITestServer.system.dto.AuthErrorResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedHashMap;
import java.util.Map;

@RestControllerAdvice(basePackages = "org.brapi.test.BrAPITestServer.system")
public class AuthExceptionHandler {

    @ExceptionHandler(AuthApiException.class)
    public ResponseEntity<AuthErrorResponse> handleAuthApiException(AuthApiException ex) {
        String message = ex.getMessage();
        return ResponseEntity.status(ex.getStatus()).body(new AuthErrorResponse(message, message));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<AuthErrorResponse> handleValidationException(MethodArgumentNotValidException ex) {
        Map<String, String> fieldErrors = new LinkedHashMap<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            fieldErrors.put(error.getField(), error.getDefaultMessage());
        }
        return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
                .body(new AuthErrorResponse("Validation failed", fieldErrors));
    }

    @ExceptionHandler(TokenExpiredException.class)
    public ResponseEntity<AuthErrorResponse> handleTokenExpired(TokenExpiredException ex) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN)
                .body(new AuthErrorResponse("Token expired", "Token expired"));
    }

    @ExceptionHandler(JWTVerificationException.class)
    public ResponseEntity<AuthErrorResponse> handleJwtVerification(JWTVerificationException ex) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(new AuthErrorResponse("Invalid token signature", "Invalid token signature"));
    }
}
