package com.ai.trackwalker.uavaccess.common;

import com.ai.trackwalker.uavaccess.flighthub.FlightHubException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ResponseStatusException;

import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestControllerAdvice
public class AccessExceptionHandler {
    @ExceptionHandler(FlightHubException.class)
    public ResponseEntity<Map<String, Object>> flightHub(FlightHubException exception) {
        Map<String, Object> body = error(
                exception.httpStatus(),
                exception.getMessage(),
                Map.of(
                        "classification", exception.classification(),
                        "vendor_code", exception.vendorCode(),
                        "request_id", exception.requestId()
                )
        );
        return ResponseEntity.status(exception.httpStatus()).body(body);
    }

    @ExceptionHandler(ResponseStatusException.class)
    public ResponseEntity<Map<String, Object>> responseStatus(ResponseStatusException exception) {
        return ResponseEntity.status(exception.getStatusCode()).body(error(
                exception.getStatusCode().value(),
                exception.getReason() == null ? "request failed" : exception.getReason(),
                Map.of()
        ));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> validation(MethodArgumentNotValidException exception) {
        String message = exception.getBindingResult().getFieldErrors().isEmpty()
                ? "request validation failed"
                : exception.getBindingResult().getFieldErrors().get(0).getDefaultMessage();
        return ResponseEntity.badRequest().body(error(400, message, Map.of()));
    }

    private Map<String, Object> error(int status, String message, Map<String, Object> detail) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put("code", String.valueOf(status));
        response.put("message", message);
        response.put("request_id", UUID.randomUUID().toString());
        response.put("timestamp", Instant.now().toString());
        response.put("detail", detail);
        return response;
    }
}
