import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { CartStoreType, SaveAllMethod } from "../types/Types";

export const useCartStore = create<CartStoreType>()(
  persist(
    (set, get) => ({
      description: "",
      setDescription: (value) => set({ description: value }),
      deliveryMethodId: null,
      setDeliveryMethodId: (value) => set({ deliveryMethodId: value }),
      addressId: null,
      setAddressId: (value) => set({ addressId: value }),
      paymentMethodId: null,
      setPaymentMethodId: (value) => set({ paymentMethodId: value }),
      carAddress: null,
      setCarAddress: (value) => set({ carAddress: value }),
      reset: () =>
        set({
          description: "",
          deliveryMethodId: null,
          addressId: null,
          paymentMethodId: null,
          carAddress: null,
        }),
      getSaveAllMethodData: (): SaveAllMethod | null => {
        const state = get();
        if (!state.deliveryMethodId || !state.paymentMethodId) {
          return null;
        }
        return {
          description: state.description,
          deliveryMethodId: state.deliveryMethodId,
          ...(state.addressId && { addressId: state.addressId }),
          paymentMethodId: state.paymentMethodId,
          ...(state.carAddress && { carAddress: state.carAddress }),
        };
      },
    }),
    {
      name: "cart-storage",
      storage: createJSONStorage(() => localStorage),
    }
  )
);
