import { env } from "../env.js";

async function coolifyFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
  if (!env.COOLIFY_API_TOKEN || !env.COOLIFY_BASE_URL) {
    throw new Error("Coolify not configured (COOLIFY_API_TOKEN / COOLIFY_BASE_URL missing)");
  }

  const res = await fetch(`${env.COOLIFY_BASE_URL}${path}`, {
    ...options,
    headers: {
      Authorization: `Bearer ${env.COOLIFY_API_TOKEN}`,
      "Content-Type": "application/json",
      ...(options.headers ?? {}),
    },
  });

  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new Error(`Coolify API ${res.status}: ${body.slice(0, 200)}`);
  }

  return res.json() as Promise<T>;
}

// Coolify only regenerates an app's Traefik labels from its fqdn field on
// deploy — patching fqdn alone leaves routing unchanged, so every domain
// add is followed by a restart (coollabsio/coolify#6281).
export async function addDomainToWebApp(hostname: string): Promise<void> {
  const appUuid = env.COOLIFY_WEB_APP_UUID;
  if (!appUuid) throw new Error("COOLIFY_WEB_APP_UUID not configured");

  const app = await coolifyFetch<{ fqdn: string | null }>(`/api/v1/applications/${appUuid}`);
  const existing = (app.fqdn ?? "")
    .split(",")
    .map((d) => d.trim())
    .filter(Boolean);

  const newUrl = `https://${hostname}`;
  if (existing.includes(newUrl)) return;

  const updated = [...existing, newUrl].join(",");
  await coolifyFetch(`/api/v1/applications/${appUuid}`, {
    method: "PATCH",
    body: JSON.stringify({ domains: updated }),
  });

  await coolifyFetch(`/api/v1/applications/${appUuid}/restart`, { method: "POST" });
}
