package com.example.volunteer.api;

import com.example.volunteer.service.SignupResult;
import com.example.volunteer.service.SignupService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * ============================================================================
 * (e) REST Controller — 报名接口
 * ============================================================================
 *
 * 【题目 / Question (e)】
 * EN — A REST API allows a volunteer to sign up for an event.
 *      URL : POST <base_url>/api/events/{eventId}/signup
 *      Body: volunteerId, hours
 *      If the event does not exist, or it is already full → HttpStatus.UNPROCESSABLE_ENTITY (422)
 *      otherwise → 201 Created
 *      Write all necessary Controller and JPA Repository code. (5 marks)
 * 中 — 报名 REST 接口：POST /api/events/{eventId}/signup，请求体含 volunteerId 与 hours。
 *      活动不存在或已满员 → 422；成功 → 201。写出 Controller 与 Repository 代码。（5 分）
 *
 * 【分层说明 / Layering】
 * EN — The Controller knows nothing about business rules: it calls the Service and translates
 *      the returned enum into an HTTP status. That is why every failure above maps to 422 and
 *      success to 201.
 * 中 — Controller 不懂业务规则：它调用 Service，把返回的枚举翻译成状态码。
 *      所以上面所有失败都映射成 422，成功映射成 201。
 *
 * 【测试 / Test with curl】
 *   curl -i -X POST http://localhost:8080/api/events/1/signup \
 *        -H "Content-Type: application/json" -d '{"volunteerId":1,"hours":3}'
 *   → 201 Created     （成功）
 *   → 422             （活动不存在 / 已满 / 重复报名 / 时数 ≤ 0）
 */
@RestController
@RequestMapping("/api/events")
public class SignupRestController {

    private final SignupService signupService;

    public SignupRestController(SignupService signupService) {
        this.signupService = signupService;
    }

    @PostMapping("/{eventId}/signup")
    public ResponseEntity<Void> signup(@PathVariable Long eventId,
                                       @RequestBody SignupRequest request) {

        SignupResult result = signupService.signup(
                eventId, request.volunteerId(), request.hours());

        return switch (result) {
            case CREATED -> ResponseEntity.status(HttpStatus.CREATED).build();          // 201
            default      -> ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).build(); // 422
        };
    }

    /**
     * 请求体 / Request body: {"volunteerId": 1, "hours": 3}
     * 用 record 最省事：Jackson 能直接反序列化（字段名即 JSON 的键）。
     */
    public record SignupRequest(Long volunteerId, int hours) { }
}
