#!/usr/bin/env node
import { execSync } from "node:child_process";

const baseUrl = (process.env.OPS_BASE_URL || process.env.APP_URL || process.env.NEXT_PUBLIC_APP_URL || "").replace(/\/+$/, "");

function fail(message) {
  console.error(`[ERROR] ${message}`);
  process.exit(1);
}

if (!baseUrl) {
  fail("Missing OPS_BASE_URL / APP_URL / NEXT_PUBLIC_APP_URL");
}

function run(command, description) {
  try {
    execSync(command, { stdio: "inherit", env: process.env, timeout: 120000 });
    console.log(`[OK] ${description}`);
  } catch (error) {
    throw new Error(`${description} failed`);
  }
}

const jobToken = process.env.CAMPAIGN_RETRY_JOB_TOKEN?.trim() || "";
const healthToken = process.env.HEALTHCHECK_TOKEN?.trim() || "";
const webhookVerifyToken = process.env.WHATSAPP_WEBHOOK_VERIFY_TOKEN?.trim() || "";
const healthHeaders = healthToken ? ` -H "Authorization: Bearer ${healthToken}"` : "";
const jobHeaders = jobToken ? ` -H "Authorization: Bearer ${jobToken}"` : "";

try {
  run("npm run -s ops:readiness", "Ops readiness");
  run(`curl -fsS ${healthHeaders} ${baseUrl}/api/health`, "Health endpoint");
  run(`curl -fsS ${jobHeaders} "${baseUrl}/api/jobs/campaign-retry?token=${encodeURIComponent(jobToken)}"`, "Campaign retry endpoint");
  if (webhookVerifyToken) {
    run(
      `curl -fsS "${baseUrl}/api/webhooks/whatsapp?hub.mode=subscribe&hub.verify_token=${encodeURIComponent(webhookVerifyToken)}&hub.challenge=ok"`,
      "Webhook verify probe"
    );
  } else {
    console.log("[SKIP] Webhook verify probe (WHATSAPP_WEBHOOK_VERIFY_TOKEN not set)");
  }
  console.log("\nSmoke checks passed");
} catch (error) {
  fail(error instanceof Error ? error.message : "Smoke checks failed");
}
