package com.nisum.exception;

import jakarta.validation.ConstraintViolationException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(WebExchangeBindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Mono<ResponseEntity<Map<String, Map<String, String>>>> handleValidationExceptions(WebExchangeBindException ex) {
        // Get the list of validation errors
        Map<String, Map<String, String>> errorMap = new HashMap<>();

        // Extract the field errors and map them to a concise structure with errorCode and status
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        for (FieldError fieldError : fieldErrors) {
            Map<String, String> errorDetails = new HashMap<>();
            errorDetails.put("errorCode", fieldError.getCode());
            errorDetails.put("status", fieldError.getDefaultMessage());
            errorMap.put(fieldError.getField(), errorDetails);
        }
// Return the error messages
        return Mono.just(ResponseEntity.badRequest().body(errorMap));
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Mono<ResponseEntity<String>> handleConstraintViolation(ConstraintViolationException ex) {
        // Extract and return error message
        return Mono.just(ResponseEntity.badRequest().body(ex.getMessage()));
    }

    @ExceptionHandler(IncorrectResultSizeDataAccessException.class)
    public ResponseEntity<Map<String, String>> handleIncorrectResultSizeException(IncorrectResultSizeDataAccessException ex) {
        Map<String, String> errorResponse = new HashMap<>();
        errorResponse.put("Duplicate", "Duplicate product not allow");
        //errorResponse.put("details", ex.getMessage());
        return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT); // HTTP 409 Conflict
    }


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleProductNotFound(Exception ex) {
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
    }
}