package com.example.volunteer.api;

import com.example.volunteer.dto.SignupSearch;
import com.example.volunteer.service.SignupQueryService;
import com.example.volunteer.service.SignupView;
import com.example.volunteer.service.VolunteerHours;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * ============================================================================
 * 查询 API — 样卷 Q4(b) 聚合 + Q4(c) 动态条件 的 HTTP 出口
 * ============================================================================
 *
 * 【题目 / Question】
 * EN — Expose the two queries of the sample paper over REST:
 *      GET /api/stats/top-volunteers?minHours=5&limit=10
 *      GET /api/signups?eventId=1&volunteerName=ali&from=2026-11-01&to=2026-11-30
 * 中 — 把样卷的两个查询做成 REST 接口：
 *      GET /api/stats/top-volunteers?minHours=5&limit=10
 *      GET /api/signups?eventId=1&volunteerName=ali&from=2026-11-01&to=2026-11-30
 *
 * 【为什么查询参数都是可选 / Why every parameter is optional】
 * EN — required = false means the client may omit any filter; the service then simply does
 *      not restrict that column. This is the HTTP face of the "any combination" requirement.
 * 中 — required = false 表示客户端可以不传任一条件；Service 就不过滤对应列。
 *      这就是“任意组合”在 HTTP 层的体现。
 */
@RestController
public class QueryApiController {

    private final SignupQueryService signupQueryService;

    public QueryApiController(SignupQueryService signupQueryService) {
        this.signupQueryService = signupQueryService;
    }

    /** 样卷 Q4(b)：累计时数排名 / top volunteers by total hours */
    @GetMapping("/api/stats/top-volunteers")
    public List<VolunteerHours> topVolunteers(@RequestParam(defaultValue = "0") int minHours,
                                              @RequestParam(defaultValue = "10") int limit) {
        return signupQueryService.topVolunteers(minHours, limit);
    }

    /** 样卷 Q4(c)：任意组合查询 / search by any combination */
    @GetMapping("/api/signups")
    public List<SignupView> search(
            @RequestParam(required = false) Long eventId,
            @RequestParam(required = false) String volunteerName,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate from,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate to) {

        SignupSearch search = new SignupSearch();
        search.setEventId(eventId);
        search.setVolunteerName(volunteerName);
        search.setFrom(from);
        search.setTo(to);

        return signupQueryService.search(search);
    }
}
