import "server-only";

/** Read a complete, consistent ledger snapshot before calling; never send a partial page. */
export async function syncExternalInquiries(snapshot: {
  source: string;
  observed_at: string;
  items: Array<{
    external_id: string; received_at: string; name: string; phone: string;
    email: string; message: string;
    status: "new" | "contacting" | "contacted" | "follow_up" | "converted" | "closed" | "excluded" | "booked" | "visited" | "no_show" | "canceled";
    extras?: Record<string, string>;
  }>;
}) {
  const key = process.env.ROOTTALE_INQUIRY_SYNC_API_KEY;
  if (!key) throw new Error("Inquiry sync key is missing");
  const response = await fetch("https://api.roottale.com/v1/inquiries/sync", {
    method: "POST", headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" },
    body: JSON.stringify(snapshot), redirect: "error", signal: AbortSignal.timeout(45_000),
  });
  // Never log the customer request or a remote error body.
  if (!response.ok) throw new Error(`Inquiry sync HTTP ${response.status}`);
  return response.json();
}
