package gc.mda.kcg.domain.stats;

import gc.mda.kcg.permission.annotation.RequirePermission;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

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

/**
 * 통계/KPI 조회 API.
 * prediction_kpi_realtime, prediction_stats_monthly, prediction_stats_daily 테이블 기반.
 */
@RestController
@RequestMapping("/api/stats")
@RequiredArgsConstructor
public class StatsController {

    private final PredictionKpiRepository kpiRepository;
    private final PredictionStatsMonthlyRepository monthlyRepository;
    private final PredictionStatsDailyRepository dailyRepository;
    private final PredictionStatsHourlyRepository hourlyRepository;

    /**
     * 실시간 KPI 전체 목록 조회
     */
    @GetMapping("/kpi")
    @RequirePermission(resource = "statistics:statistics", operation = "READ")
    public List<PredictionKpi> getKpi() {
        return kpiRepository.findAll();
    }

    /**
     * 월별 통계 조회
     * @param from 시작 월 (예: 2025-10)
     * @param to   종료 월 (예: 2026-04)
     */
    @GetMapping("/monthly")
    @RequirePermission(resource = "statistics:statistics", operation = "READ")
    public List<PredictionStatsMonthly> getMonthly(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate from,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate to
    ) {
        return monthlyRepository.findByStatMonthBetweenOrderByStatMonthAsc(from, to);
    }

    /**
     * 일별 통계 조회
     * @param from 시작 날짜 (예: 2026-04-01)
     * @param to   종료 날짜 (예: 2026-04-07)
     */
    @GetMapping("/daily")
    @RequirePermission(resource = "statistics:statistics", operation = "READ")
    public List<PredictionStatsDaily> getDaily(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate from,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate to
    ) {
        return dailyRepository.findByStatDateBetweenOrderByStatDateAsc(from, to);
    }

    /**
     * 시간별 통계 조회 (최근 N시간)
     * @param hours 조회 시간 범위 (기본 24시간)
     */
    @GetMapping("/hourly")
    @RequirePermission(resource = "statistics:statistics", operation = "READ")
    public List<PredictionStatsHourly> getHourly(
            @RequestParam(defaultValue = "24") int hours
    ) {
        OffsetDateTime to = OffsetDateTime.now();
        OffsetDateTime from = to.minusHours(hours);
        return hourlyRepository.findByStatHourBetweenOrderByStatHourAsc(from, to);
    }
}
