import { create } from "zustand";
import { persist } from "zustand/middleware";

export type LocalCartItem = {
  productId: number;
  variantId: string;
  quantity: number;
};

export type LocalCartStoreType = {
  items: LocalCartItem[];
  addItem: (item: LocalCartItem) => void;
  updateItem: (productId: number, variantId: string, quantity: number) => void;
  removeItem: (productId: number, variantId: string) => void;
  getItem: (productId: number, variantId: string) => LocalCartItem | undefined;
  clearCart: () => void;
};

export const useLocalCartStore = create<LocalCartStoreType>()(
  persist(
    (set, get) => ({
      items: [],

      addItem: (item: LocalCartItem) => {
        const existingItem = get().items.find(
          (i) =>
            i.productId === item.productId && i.variantId === item.variantId
        );

        if (existingItem) {
          set((state) => ({
            items: state.items.map((i) =>
              i.productId === item.productId && i.variantId === item.variantId
                ? { ...i, quantity: i.quantity + item.quantity }
                : i
            ),
          }));
        } else {
          set((state) => ({
            items: [...state.items, item],
          }));
        }
      },

      updateItem: (productId: number, variantId: string, quantity: number) => {
        set((state) => ({
          items: state.items.map((item) =>
            item.productId === productId && item.variantId === variantId
              ? { ...item, quantity }
              : item
          ),
        }));
      },

      removeItem: (productId: number, variantId: string) => {
        set((state) => ({
          items: state.items.filter(
            (item) =>
              !(item.productId === productId && item.variantId === variantId)
          ),
        }));
      },

      getItem: (productId: number, variantId: string) => {
        return get().items.find(
          (item) => item.productId === productId && item.variantId === variantId
        );
      },

      clearCart: () => {
        set({ items: [] });
      },
    }),
    {
      name: "local-cart-storage",
    }
  )
);
