// zustand/receiptStore.ts
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

type ReceiptItemMap = {
  [id: string | number]: {
    quantity: number;
  };
};

type ReceiptStore = {
  items: ReceiptItemMap;
  slug: string | null;
  setSlug: (slug: string) => void;
  increment: (id: string | number) => void;
  decrement: (id: string | number) => void;
  setQuantity: (id: string | number, quantity: number) => void;
  clear: () => void;
};

export const useReceiptStore = create<ReceiptStore>()(
  persist(
    (set) => ({
      items: {},
      slug: null,
      setSlug: (slug) => set({ slug }),
      clear: () => set({ items: {}, slug: null }),
      increment: (id) =>
        set((state) => {
          const current = state.items[id]?.quantity || 0;
          return {
            items: {
              ...state.items,
              [id]: { quantity: current + 1 },
            },
          };
        }),
      decrement: (id) =>
        set((state) => {
          const current = state.items[id]?.quantity || 0;
          if (current <= 0) return {};
          return {
            items: {
              ...state.items,
              [id]: { quantity: current - 1 },
            },
          };
        }),
      setQuantity: (id, quantity) =>
        set((state) => ({
          items: {
            ...state.items,
            [id]: { quantity },
          },
        })),
    }),
    {
      name: "receipt-storage",
      storage: createJSONStorage(() => localStorage),
    }
  )
);
