import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { Product } from '@/domain/entities';
import { IWishlistRepository } from '@/application/ports/IWishlistRepository';

interface WishlistState {
  items: Product[];
  _setItems: (items: Product[]) => void;
}

export const useWishlistStore = create<WishlistState>()(
  persist(
    (set) => ({
      items: [],
      _setItems: (items) => set({ items }),
    }),
    { name: 'kott-gard-wishlist' }
  )
);

export class ZustandWishlistRepository implements IWishlistRepository {
  getItems(): Product[] {
    return useWishlistStore.getState().items;
  }

  private setItems(items: Product[]): void {
    useWishlistStore.getState()._setItems(items);
  }

  addItem(product: Product): void {
    if (!this.isInWishlist(product.id)) {
      this.setItems([...this.getItems(), product]);
    }
  }

  removeItem(productId: string): void {
    this.setItems(this.getItems().filter((p) => p.id !== productId));
  }

  isInWishlist(productId: string): boolean {
    return this.getItems().some((p) => p.id === productId);
  }

  toggleItem(product: Product): void {
    if (this.isInWishlist(product.id)) {
      this.removeItem(product.id);
    } else {
      this.addItem(product);
    }
  }
}