package com.nebula.erp.product.config;

import org.springframework.http.HttpStatus;
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 java.util.Map;
import com.nebula.erp.product.utility.ApiResponse;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponse<Map<String, Object>>> handleValidationExceptions(MethodArgumentNotValidException ex) {

        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .findFirst() // Get the first error
                .map(error -> error.getField() + ": " + error.getDefaultMessage()) // Format the error message
                .orElse("Validation error occurred"); // Default message if no error is found

        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ApiResponse<>("error", HttpStatus.BAD_REQUEST.value(), errorMessage, null));
    }
}