import { create } from 'zustand';

console.log('✅ pagination store created');

type TableKey = string;

interface TablePagination {
  page: number;
  pageSize: number;
}

interface TableFilter {
  items: any[];
}

interface PaginationState {
  tables: Record<TableKey, TablePagination>;
  filters: Record<TableKey, TableFilter>;
  setPagination: (table: TableKey, next: Partial<TablePagination>) => void;
  resetPagination: (table: TableKey) => void;
  setFilter: (table: TableKey, next: Partial<TableFilter>) => void;
  resetFilter: (table: TableKey) => void;
}

export const usePaginationStore = create<PaginationState>((set) => ({
  tables: {},
  filters: {},
  setPagination: (table, next) =>
    set((state) => {
      const prev = state.tables[table] ?? { page: 0, pageSize: 10 };
      return {
        tables: {
          ...state.tables,
          [table]: {
            page: next.page ?? prev.page,
            pageSize: next.pageSize ?? prev.pageSize,
          },
        },
      };
    }),
  resetPagination: (table) =>
    set((state) => ({
      tables: {
        ...state.tables,
        [table]: { page: 0, pageSize: state.tables[table]?.pageSize ?? 10 },
      },
    })),
  setFilter: (table, next) =>
    set((state) => ({
      filters: {
        ...state.filters,
        [table]: {
          items: next.items ?? state.filters[table]?.items ?? [],
        },
      },
    })),
  resetFilter: (table) =>
    set((state) => ({
      filters: {
        ...state.filters,
        [table]: { items: [] },
      },
    })),
}));
