package com.example.todo;

import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestControllerAdvice
public class ApiErrors {
    private ResponseEntity<Map<String,Object>> error(int status,String message,Object details) {
        Map<String,Object> body=new LinkedHashMap<>();
        body.put("timestamp",Instant.now().toString()); body.put("status",status);
        body.put("message",message); body.put("details",details);
        return ResponseEntity.status(status).body(body);
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    ResponseEntity<Map<String,Object>> validation(MethodArgumentNotValidException ex) {
        Map<String,String> fields=new LinkedHashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(e -> fields.put(e.getField(),e.getDefaultMessage()));
        return error(400,"Validation failed",fields);
    }
    @ExceptionHandler(HttpMessageNotReadableException.class)
    ResponseEntity<Map<String,Object>> malformed(HttpMessageNotReadableException ex) {
        return error(400,"Malformed JSON or incorrect field type",Map.of());
    }
    @ExceptionHandler(ResponseStatusException.class)
    ResponseEntity<Map<String,Object>> status(ResponseStatusException ex) {
        return error(ex.getStatusCode().value(),ex.getReason(),Map.of());
    }
    @ExceptionHandler(DuplicateKeyException.class)
    ResponseEntity<Map<String,Object>> duplicate(DuplicateKeyException ex) {
        return error(409,"Email already registered",Map.of());
    }
}
