#!/usr/bin/env node

const baseUrl = process.env.CAMPAIGN_RETRY_JOB_URL?.trim()
  || process.env.APP_URL?.trim()
  || process.env.NEXT_PUBLIC_APP_URL?.trim();

if (!baseUrl) {
  console.error("Missing CAMPAIGN_RETRY_JOB_URL / APP_URL / NEXT_PUBLIC_APP_URL");
  process.exit(1);
}

const endpoint = baseUrl.endsWith("/api/jobs/campaign-retry")
  ? baseUrl
  : `${baseUrl.replace(/\/+$/, "")}/api/jobs/campaign-retry`;

const token = process.env.CAMPAIGN_RETRY_JOB_TOKEN?.trim();
const tenantId = process.env.CAMPAIGN_RETRY_TENANT_ID?.trim();
const campaignId = process.env.CAMPAIGN_RETRY_CAMPAIGN_ID?.trim();
const recipientBatchSize = Number(process.env.CAMPAIGN_RETRY_BATCH_SIZE);
const maxCampaigns = Number(process.env.CAMPAIGN_RETRY_MAX_CAMPAIGNS);

const payload = {
  ...(tenantId ? { tenantId } : {}),
  ...(campaignId ? { campaignId } : {}),
  ...(Number.isInteger(recipientBatchSize) && recipientBatchSize > 0 ? { recipientBatchSize } : {}),
  ...(Number.isInteger(maxCampaigns) && maxCampaigns > 0 ? { maxCampaigns } : {})
};

const headers = {
  "content-type": "application/json"
};

if (token) {
  headers.Authorization = `Bearer ${token}`;
}

try {
  const response = await fetch(endpoint, {
    method: "POST",
    headers,
    body: JSON.stringify(payload)
  });

  const bodyText = await response.text();

  if (!response.ok) {
    console.error(`Campaign retry job failed: ${response.status} ${response.statusText}`);
    console.error(bodyText);
    process.exit(1);
  }

  console.log(bodyText);
} catch (error) {
  console.error(`Failed to trigger campaign retry job: ${error instanceof Error ? error.message : String(error)}`);
  process.exit(1);
}
