package com.example.volunteer.web;

import com.example.volunteer.dto.EventForm;
import com.example.volunteer.model.Event;
import com.example.volunteer.repository.EventRepository;
import jakarta.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

/**
 * ============================================================================
 * 表单控制器 — 样卷 Q4(e) + Q5(a)
 * ============================================================================
 *
 * 【题目 / Question】
 * EN — (e) Complete the essential HTML tags for the item form, and (a) explain whether
 *      validation is necessary and which Spring components are most suitable.
 * 中 — (e) 补全新增表单的关键 HTML 标签；(a) 说明校验是否必要、哪些 Spring 组件最合适。
 *
 * 【三个要点 / Three points】
 * 1. GET 显示表单：model 里必须放一个空对象（模板的 th:object 要靠它）
 * 2. POST 接收：@Valid 触发 Bean Validation，BindingResult 收集错误
 *    → 有错就回到同一个视图，让 th:errors 显示（而不是抛 400 页面）
 * 3. 成功后 redirect:/events（Post-Redirect-Get），避免刷新重复提交
 *
 * 【分层的答案 / The layered answer】
 * EN — Field-level rules live on EventForm (annotations); rules that need other data
 *      (e.g. "venue already booked that day") belong to a service. Client-side `required`
 *      is only a convenience and can be bypassed.
 * 中 — 字段级规则写在 EventForm 的注解上；需要查其他数据的规则（如“场地当天已被占用”）
 *      属于 Service；前端 required 只是体验优化，可被绕过。
 */
@Controller
@RequestMapping("/events")
public class EventFormController {

    private final EventRepository eventRepository;

    public EventFormController(EventRepository eventRepository) {
        this.eventRepository = eventRepository;
    }

    /** 显示空表单 / Show an empty form */
    @GetMapping("/new")
    public String showForm(Model model) {
        model.addAttribute("eventForm", new EventForm());
        return "event-form";
    }

    /** 提交表单 / Handle the submission */
    @PostMapping
    public String create(@Valid @ModelAttribute("eventForm") EventForm form,
                         BindingResult bindingResult) {

        // 校验失败：不抛异常，回到表单页并回显错误
        if (bindingResult.hasErrors()) {
            return "event-form";
        }

        Event event = new Event(form.getTitle(), form.getEventDate(),
                                form.getLocation(), form.getCapacity());
        eventRepository.save(event);

        // PRG：重定向到列表页，刷新不会重复提交
        return "redirect:/events";
    }
}
