import { create } from 'zustand';
import { api, ApiError } from '../api/client';
import type { ClosureSummary, MonthClosure } from '../api/types';
import { currentMonthKey, shiftMonthKey } from '../lib/month';

interface ClosureState {
  period: string;
  closure: MonthClosure | null;
  summary: ClosureSummary | null;
  busy: boolean;
  error: string | null;

  load: () => Promise<void>;
  setPeriod: (period: string) => Promise<void>;
  prevPeriod: () => Promise<void>;
  nextPeriod: () => Promise<void>;
  confirm: () => Promise<void>;
}

const useClosureStore = create<ClosureState>((set, get) => ({
  period: currentMonthKey(),
  closure: null,
  summary: null,
  busy: false,
  error: null,

  load: async () => {
    try {
      const res = await api.get<{ closure: MonthClosure; summary: ClosureSummary }>(
        `/closure?period=${get().period}`
      );
      set({ closure: res.closure, summary: res.summary, error: null });
    } catch {
      set({ error: 'Nepodařilo se načíst uzávěrku' });
    }
  },

  setPeriod: async (period) => {
    set({ period });
    await get().load();
  },

  prevPeriod: async () => {
    await get().setPeriod(shiftMonthKey(get().period, -1));
  },

  nextPeriod: async () => {
    await get().setPeriod(shiftMonthKey(get().period, 1));
  },

  confirm: async () => {
    set({ busy: true, error: null });
    try {
      await api.post('/closure/confirm', { period: get().period });
      await get().load();
    } catch (err) {
      set({ error: err instanceof ApiError ? err.message : 'Potvrzení se nezdařilo' });
    } finally {
      set({ busy: false });
    }
  },
}));

export default useClosureStore;
