import { create } from 'zustand';
import {
  getEnforcementRecords,
  toLegacyRecord,
  type EnforcementRecord,
  type LegacyEnforcementRecord,
} from '@/services/enforcement';

interface EnforcementStore {
  /** 원본 API 단속 기록 */
  rawRecords: EnforcementRecord[];
  /** 하위 호환용 레거시 형식 */
  records: LegacyEnforcementRecord[];
  /** 페이지네이션 */
  totalElements: number;
  totalPages: number;
  /** 로딩/에러 */
  loading: boolean;
  error: string | null;
  loaded: boolean;
  /** API 호출 */
  load: (params?: { violationType?: string; page?: number; size?: number }) => Promise<void>;
}

export const useEnforcementStore = create<EnforcementStore>((set, get) => ({
  rawRecords: [],
  records: [],
  totalElements: 0,
  totalPages: 0,
  loading: false,
  error: null,
  loaded: false,

  load: async (params) => {
    // 중복 호출 방지 (파라미터 없는 기본 호출은 loaded 체크)
    if (!params && get().loaded && !get().error) return;

    set({ loading: true, error: null });
    try {
      const res = await getEnforcementRecords(params);
      set({
        rawRecords: res.content,
        records: res.content.map(toLegacyRecord),
        totalElements: res.totalElements,
        totalPages: res.totalPages,
        loaded: true,
        loading: false,
      });
    } catch (err) {
      set({ error: err instanceof Error ? err.message : String(err), loading: false });
    }
  },
}));
