export type GuestOrderRef = {
  orderId: string;
  trackingToken: string;
  orderNumber: string;
  createdAt: string;
  cafeId: string;
  branchId: string;
  tableId: string;
};

const STORAGE_KEY = "meezi_guest_orders";

export function saveGuestOrder(ref: GuestOrderRef): void {
  if (typeof window === "undefined") return;
  const list = loadGuestOrders();
  const filtered = list.filter((o) => o.orderId !== ref.orderId);
  const next = [ref, ...filtered].slice(0, 30);
  localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
}

export function loadGuestOrders(): GuestOrderRef[] {
  if (typeof window === "undefined") return [];
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (!raw) return [];
    const parsed = JSON.parse(raw) as GuestOrderRef[];
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}

export function ordersForTable(orders: GuestOrderRef[], cafeId: string, tableId: string) {
  return orders.filter((o) => o.cafeId === cafeId && o.tableId === tableId);
}
