const targetUrl = process.argv[2];

try {
  if (!targetUrl) throw new Error("Usage: node check-preview.mjs https://example.com/page");

  const endpoint = new URL("https://previewchecks.com/api/v1/check");
  endpoint.searchParams.set("url", targetUrl);
  const response = await fetch(endpoint, { signal: AbortSignal.timeout(20_000) });
  if (!response.ok) throw new Error(`PreviewChecks API returned HTTP ${response.status}.`);

  const report = await response.json();
  if (
    report.schemaVersion !== 2 ||
    !["pass", "notice", "warning", "error"].includes(report.summary?.status) ||
    !Array.isArray(report.server?.issues) ||
    !Array.isArray(report.issues)
  ) {
    throw new Error("Unsupported PreviewChecks response. Review the API contract.");
  }
  if (report.server.issues.some((issue) => issue.id === "probe-service-unavailable")) {
    throw new Error(
      "The preview check did not complete. Run it again before relying on the result.",
    );
  }

  console.log(JSON.stringify({ summary: report.summary, issues: report.issues }, null, 2));
  process.exitCode = report.summary.status === "error" ? 1 : 0;
} catch (error) {
  console.error(error instanceof Error ? error.message : "The preview check could not finish.");
  process.exitCode = 1;
}
