package com.zioinfo.mes.analytics;

import com.zioinfo.mes.analytics.mapper.AnalyticsMapper;
import com.zioinfo.mes.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 분석/KPI API (생산·품질·재고) — BI 피드 겸용. 조회 Viewer+.
 */
@RestController
@RequestMapping("/api/mes/analytics")
@RequiredArgsConstructor
public class AnalyticsController {

    private final AnalyticsMapper mapper;

    /** 생산 KPI. */
    @GetMapping("/production-kpi")
    public ApiResponse<Map<String, Object>> productionKpi(@RequestParam(defaultValue = "30") int days) {
        return ApiResponse.ok(mapper.productionKpi(days));
    }

    /** 품질 KPI. */
    @GetMapping("/quality-kpi")
    public ApiResponse<Map<String, Object>> qualityKpi(@RequestParam(defaultValue = "30") int days) {
        return ApiResponse.ok(mapper.qualityKpi(days));
    }

    /** 재고 KPI. */
    @GetMapping("/inventory-kpi")
    public ApiResponse<Map<String, Object>> inventoryKpi() {
        return ApiResponse.ok(mapper.inventoryKpi());
    }

    /** 일자별 생산 추이. */
    @GetMapping("/daily-production")
    public ApiResponse<List<Map<String, Object>>> dailyProduction(@RequestParam(defaultValue = "14") int days) {
        return ApiResponse.ok(mapper.dailyProduction(days));
    }

    /** 품목별 생산량 Top. */
    @GetMapping("/top-items")
    public ApiResponse<List<Map<String, Object>>> topItems(@RequestParam(defaultValue = "30") int days,
                                                          @RequestParam(defaultValue = "5") int limit) {
        return ApiResponse.ok(mapper.topItems(days, limit));
    }

    /** BI 피드 — 생산·품질·재고 KPI 통합(GUARDiA BI 연동용). */
    @GetMapping("/bi-feed")
    public ApiResponse<Map<String, Object>> biFeed(@RequestParam(defaultValue = "30") int days) {
        Map<String, Object> feed = new LinkedHashMap<>();
        feed.put("production", mapper.productionKpi(days));
        feed.put("quality", mapper.qualityKpi(days));
        feed.put("inventory", mapper.inventoryKpi());
        feed.put("dailyProduction", mapper.dailyProduction(days));
        feed.put("topItems", mapper.topItems(days, 10));
        return ApiResponse.ok(feed);
    }
}
