package com.owrawww.controller;

import com.owrawww.domain.Quote;
import com.owrawww.service.QuoteService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
@RequestMapping("/bbs/insertQuote")
@RequiredArgsConstructor
public class QuoteController {

    private final QuoteService quoteService;

    @GetMapping
    public String quoteForm(@ModelAttribute Quote quote) {
        return "insertQuote";
    }

    @PostMapping
    @ResponseBody
    public ResponseEntity<Map<String, Object>> quoteSubmit(@Valid @ModelAttribute Quote quote,
                                                           BindingResult bindingResult) {
        Map<String, Object> result = new HashMap<>();
        if (bindingResult.hasErrors()) {
            List<String> errors = bindingResult.getFieldErrors().stream()
                    .map(e -> e.getField() + ": " + e.getDefaultMessage())
                    .collect(Collectors.toList());
            result.put("success", false);
            result.put("message", "입력값을 확인해주세요.");
            result.put("errors", errors);
            return ResponseEntity.badRequest().body(result);
        }
        boolean success = quoteService.submit(quote);
        result.put("success", success);
        if (!success) {
            result.put("message", "처리 중 오류가 발생했습니다. 다시 시도해주세요.");
        }
        return ResponseEntity.ok(result);
    }
}
