// stores/attendance-sheet-store.ts
import { create } from 'zustand';
import axiosInstance from '@/utils/axios';
import { AttendanceSheetList, AttendanceSheetPageFilterParams, AttendanceSheet } from '@/shared/types/attendance-sheet';
import { absenceEndpoints } from '../endpoints/absence';

type AttendanceSheetStore = {
  loading: boolean;
  error: string | null;
  attendanceSheets: AttendanceSheet[];
  totalElements: number;
  fetchAttendanceSheetsPage: (params?: AttendanceSheetPageFilterParams) => Promise<void>;
};

export const useAttendanceSheetStore = create<AttendanceSheetStore>((set) => ({
  loading: false,
  error: null,
  attendanceSheets: [],
  totalElements: 0,
  fetchAttendanceSheetsPage: async (params) => {
    set({ loading: true, error: null });
    try {
      const response = await axiosInstance.get(absenceEndpoints.absence.attendanceSheet.searchAttendanceSheets, {
        params,
      });

      const { content, totalElements } = response.data as AttendanceSheetList;
      set({
        attendanceSheets: content || [],
        totalElements: totalElements || 0,
        loading: false,
      });
    } catch (error: any) {
      set({
        error: error.message || 'Failed to fetch attendance sheets',
        loading: false,
      });
      throw error;
    }
  },
}));