import { create } from 'zustand';
import type { KpiMetric, MonthlyTrend, ViolationType } from '@/data/mock/kpi';
import {
  getKpiMetrics,
  getMonthlyStats,
  toKpiMetric,
  toMonthlyTrend,
  toViolationTypes,
} from '@/services/kpi';
import { toDateParam } from '@shared/utils/dateFormat';

interface KpiStore {
  metrics: KpiMetric[];
  monthly: MonthlyTrend[];
  violationTypes: ViolationType[];
  loaded: boolean;
  loading: boolean;
  error: string | null;
  load: () => Promise<void>;
}

export const useKpiStore = create<KpiStore>((set, get) => ({
  metrics: [],
  monthly: [],
  violationTypes: [],
  loaded: false,
  loading: false,
  error: null,
  load: async () => {
    if (get().loading) return;
    set({ loading: true, error: null });
    try {
      // 6개월 범위로 월별 통계 조회
      const now = new Date();
      const from = new Date(now.getFullYear(), now.getMonth() - 6, 1);

      const [kpiData, monthlyData] = await Promise.all([
        getKpiMetrics(),
        getMonthlyStats(toDateParam(from), toDateParam(now)),
      ]);

      set({
        metrics: kpiData.map(toKpiMetric),
        monthly: monthlyData.map(toMonthlyTrend),
        violationTypes: toViolationTypes(monthlyData),
        loaded: true,
        loading: false,
      });
    } catch (err) {
      set({
        error: err instanceof Error ? err.message : 'KPI 데이터 로드 실패',
        loading: false,
      });
    }
  },
}));
