package kr.iotdoor.boot.web;

import jakarta.validation.Valid;
import kr.iotdoor.boot.model.contact.ContactRequest;
import kr.iotdoor.boot.model.contact.ContactSubmission;
import kr.iotdoor.boot.service.ContactSubmissionService;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/api/contact")
public class ContactApiController {

    private final ContactSubmissionService contactSubmissionService;

    public ContactApiController(ContactSubmissionService contactSubmissionService) {
        this.contactSubmissionService = contactSubmissionService;
    }

    @PostMapping
    public ResponseEntity<Map<String, Object>> submit(@Valid @RequestBody ContactRequest request) {
        ContactSubmission submission = contactSubmissionService.submit(request);

        Map<String, Object> body = new LinkedHashMap<>();
        body.put("success", true);
        body.put("message", "문의가 정상적으로 접수되었습니다.");
        body.put("submittedAt", submission.getSubmittedAt().toString());
        return ResponseEntity.ok(body);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidation(MethodArgumentNotValidException exception) {
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("success", false);

        Map<String, String> errors = new LinkedHashMap<>();
        for (FieldError error : exception.getBindingResult().getFieldErrors()) {
            errors.putIfAbsent(error.getField(), error.getDefaultMessage());
        }

        body.put("message", errors.values().stream().findFirst().orElse("입력값을 확인해주세요."));
        body.put("errors", errors);
        return ResponseEntity.badRequest().body(body);
    }
}
