// Tiny sessionStorage handoff so the sales tax report's "Record a tax
// payment" button can land on #bills with the New-bill form already open and
// prefilled (agency vendor, one line categorized to the Sales Tax Payable
// account, the owed amount) — mechanical extension of vendorFilterHandoff.ts
// (see that file and invoices/customerFilterHandoff.ts for why this is a
// sessionStorage handoff rather than a hash query param): best-effort, never
// fatal if storage is unavailable, consumed exactly once so a later plain
// navigation to #bills doesn't keep reopening a stale prefilled form.

const KEY = "bills:pendingNewBillPrefill";

export interface NewBillPrefill {
  vendorId: string;
  description: string;
  /** Dollars-and-cents string ("123.45") — the bill form's unit-price shape. */
  unitPrice: string;
  categoryAccountId: string;
}

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

export function consumePendingNewBillPrefill(): NewBillPrefill | null {
  try {
    const raw = window.sessionStorage.getItem(KEY);
    if (raw) {
      window.sessionStorage.removeItem(KEY);
      const parsed = JSON.parse(raw) as Partial<NewBillPrefill>;
      if (
        typeof parsed.vendorId === "string" &&
        typeof parsed.description === "string" &&
        typeof parsed.unitPrice === "string" &&
        typeof parsed.categoryAccountId === "string"
      ) {
        return parsed as NewBillPrefill;
      }
    }
  } catch {
    // best-effort only
  }
  return null;
}
