import { captureCaught } from '@/lib/observability';

export const STORAGE_KEY = 'multideal:wishlist:v1';
const MAX_ENTRIES = 200;

export type AnonWishlistItem = { dealId: string; addedAt: number };

function isBrowser(): boolean {
  return typeof window !== 'undefined' && typeof localStorage !== 'undefined';
}

function read(): AnonWishlistItem[] {
  if (!isBrowser()) return [];
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [];
    return parsed.filter(
      (x): x is AnonWishlistItem =>
        x != null && typeof x.dealId === 'string' && typeof x.addedAt === 'number',
    );
  } catch (err) {
    captureCaught(err, { scope: 'anonWishlistStore.read', severity: 'warning' });
    return [];
  }
}

function write(items: AnonWishlistItem[]): void {
  if (!isBrowser()) return;
  const trimmed = items.length > MAX_ENTRIES ? items.slice(items.length - MAX_ENTRIES) : items;
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(trimmed));
  } catch (err) {
    if (err instanceof DOMException && err.name === 'QuotaExceededError') {
      try {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(trimmed.slice(50)));
      } catch (retryErr) {
        captureCaught(retryErr, { scope: 'anonWishlistStore.write.retry', severity: 'warning' });
      }
    } else {
      captureCaught(err, { scope: 'anonWishlistStore.write', severity: 'warning' });
    }
  }
}

export function getAnonWishlist(): AnonWishlistItem[] {
  return read();
}

export function addToAnonWishlist(dealId: string): void {
  const items = read();
  if (items.some((x) => x.dealId === dealId)) return;
  items.push({ dealId, addedAt: Date.now() });
  write(items);
}

export function removeFromAnonWishlist(dealId: string): void {
  write(read().filter((x) => x.dealId !== dealId));
}

export function hasInAnonWishlist(dealId: string): boolean {
  return read().some((x) => x.dealId === dealId);
}

export function clearAnonWishlist(): void {
  if (!isBrowser()) return;
  try {
    localStorage.removeItem(STORAGE_KEY);
  } catch (err) {
    captureCaught(err, { scope: 'anonWishlistStore.clear', severity: 'warning' });
  }
}

export function countAnonWishlist(): number {
  return read().length;
}

export function getAnonWishlistIds(): string[] {
  return read().map((x) => x.dealId);
}
