import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { CartItem, Product, ProductCustomization } from '@/domain/entities';
import { CartDomainService } from '@/domain/services/CartDomainService';
import { ICartRepository } from '@/application/ports/ICartRepository';

interface CartState {
  items: CartItem[];
}

interface CartActions {
  _setItems: (items: CartItem[]) => void;
}

/**
 * INFRASTRUCTURE — Zustand store (state + persistence only)
 */
export const useCartStore = create<CartState & CartActions>()(
  persist(
    (set) => ({
      items: [],
      _setItems: (items) => set({ items }),
    }),
    { name: 'kott-gard-cart' }
  )
);

/**
 * INFRASTRUCTURE — Cart repository adapter (implements application port)
 */
export class ZustandCartRepository implements ICartRepository {
  getItems(): CartItem[] {
    return useCartStore.getState().items;
  }

  setItems(items: CartItem[]): void {
    useCartStore.getState()._setItems(items);
  }

  addItem(
    product: Product,
    customization: ProductCustomization,
    customizationLabel: string,
    quantity = 1
  ): void {
    const items = this.getItems();
    const next = CartDomainService.addItem(
      items,
      product,
      customization,
      customizationLabel,
      quantity
    );
    this.setItems(next);
  }

  removeItem(id: string): void {
    this.setItems(CartDomainService.removeItem(this.getItems(), id));
  }

  updateQuantity(id: string, quantity: number): void {
    this.setItems(
      CartDomainService.updateQuantity(this.getItems(), id, quantity)
    );
  }

  clearCart(): void {
    this.setItems([]);
  }
}