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

const STORAGE_KEY = "meezi_guest_orders";

function isValidRef(ref: GuestOrderRef): boolean {
  return !!(
    ref.orderId?.trim() &&
    ref.trackingToken?.trim() &&
    ref.orderNumber?.trim() &&
    ref.cafeId?.trim() &&
    ref.tableId?.trim()
  );
}

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

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[];
    if (!Array.isArray(parsed)) return [];
    return parsed.filter(isValidRef);
  } catch {
    return [];
  }
}

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