/**
 * embed Flock Direct 联调：POST /api/flock/quotes → 轮询 GET /api/quotes/:id
 * 用法: npx tsx scripts/smoke-flock-embed-direct.ts
 */
import { randomUUID } from "node:crypto";

const BASE = process.env.SMOKE_BASE_URL ?? "http://127.0.0.1:3000";
const TOKEN = process.env.SMOKE_HOST_TOKEN ?? "demo-host-token";
const CUSTOMER = process.env.SMOKE_CUSTOMER_ID ?? "CUST_001";

function tomorrowMmDdYyyy(): string {
  const d = new Date();
  d.setDate(d.getDate() + 1);
  const mm = String(d.getMonth() + 1).padStart(2, "0");
  const dd = String(d.getDate()).padStart(2, "0");
  return `${mm}/${dd}/${d.getFullYear()}`;
}

async function main(): Promise<void> {
  const requestId = randomUUID();
  const body = {
    request_id: requestId,
    customer_id: CUSTOMER,
    flock_input: {
      pickup_date: tomorrowMmDdYyyy(),
      pickup_zip: "90001",
      delivery_zip: "75201",
      pallet_count: 6,
      total_weight: { value: 10000, unit: "lb" },
      dimensions: { length: 48, width: 40, height: 48, unit: "in" },
    },
  };

  console.log(`[smoke-flock] POST ${BASE}/api/flock/quotes`);
  const createRes = await fetch(`${BASE}/api/flock/quotes`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${TOKEN}`,
      "X-Customer-Id": CUSTOMER,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  });
  const created = (await createRes.json()) as {
    code: number;
    message?: string;
    data?: { quote_id: string };
  };
  if (created.code !== 0 || !created.data?.quote_id) {
    console.error("[smoke-flock] create FAIL", createRes.status, created);
    process.exit(1);
  }
  const quoteId = created.data.quote_id;
  console.log(`[smoke-flock] quote_id=${quoteId} polling…`);

  const deadline = Date.now() + 120_000;
  while (Date.now() < deadline) {
    const getRes = await fetch(`${BASE}/api/quotes/${quoteId}`, {
      headers: {
        Authorization: `Bearer ${TOKEN}`,
        "X-Customer-Id": CUSTOMER,
      },
    });
    const detail = (await getRes.json()) as {
      code: number;
      message?: string;
      data?: {
        status: string;
        error_message?: string;
        flock?: { lines?: Array<{ label: string; total: number }> };
      };
    };
    if (detail.code !== 0 || !detail.data) {
      console.error("[smoke-flock] get FAIL", detail);
      process.exit(1);
    }
    const st = detail.data.status;
    if (st === "processing") {
      await new Promise((r) => setTimeout(r, 2000));
      continue;
    }
    if (st === "done") {
      const lines = detail.data.flock?.lines ?? [];
      console.log(
        `[smoke-flock] OK lines=${lines.length} ` +
          lines.map((l) => `${l.label}:$${l.total}`).join(", "),
      );
      if (lines.length < 1) process.exit(1);
      return;
    }
    console.error(
      `[smoke-flock] status=${st} ${detail.data.error_message ?? detail.message}`,
    );
    process.exit(1);
  }
  console.error("[smoke-flock] timeout");
  process.exit(1);
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
