// Tiny sessionStorage handoff so "Receive" on a purchase order can land on
// #bills with the New-bill form already open and prefilled with what's still
// outstanding — the same pattern (and the same best-effort, consumed-exactly-
// once discipline) as bills/newBillPrefillHandoff.ts and the bank flows.
//
// A hash query param would have to carry a whole line set through the URL,
// where a stale back-button would silently re-open a prefill built from
// quantities that have since changed. Consumed once, so a later plain
// navigation to #bills doesn't keep reopening it.
//
// The payload is exactly what POST /api/c/purchase-orders/:id/receive returned
// (server/src/purchaseOrders.ts), plus the purchase order it came from so the
// bill form can say so. Nothing is recomputed on this side: the server already
// subtracted what's sitting on unentered bills and said so in `notice`.

import type { ReceivePayload } from "./poTypes";

const KEY = "purchaseOrders:pendingReceive";

export interface PendingReceive extends ReceivePayload {
  poId: string;
  poNo: string | null;
}

export function setPendingReceive(pending: PendingReceive): void {
  try {
    window.sessionStorage.setItem(KEY, JSON.stringify(pending));
  } catch {
    // best-effort only
  }
}

export function consumePendingReceive(): PendingReceive | null {
  try {
    const raw = window.sessionStorage.getItem(KEY);
    if (raw) {
      window.sessionStorage.removeItem(KEY);
      const parsed = JSON.parse(raw) as Partial<PendingReceive>;
      if (
        typeof parsed.vendorId === "string" &&
        typeof parsed.billDate === "string" &&
        Array.isArray(parsed.lines)
      ) {
        return parsed as PendingReceive;
      }
    }
  } catch {
    // best-effort only
  }
  return null;
}
