/**
 * Shared helper — triggers PMTiles rebuild via webhook after sync operations.
 * The webhook server (pmtiles-webhook systemd service on satra) runs
 * `docker run architools-tippecanoe` to regenerate overview tiles.
 */

const WEBHOOK_URL = process.env.N8N_WEBHOOK_URL || "";

export async function firePmtilesRebuild(
  event: string,
  metadata?: Record<string, unknown>,
): Promise<{ ok: boolean; alreadyRunning?: boolean }> {
  if (!WEBHOOK_URL) {
    console.warn("[pmtiles-webhook] N8N_WEBHOOK_URL not configured — skipping rebuild trigger");
    return { ok: false };
  }

  try {
    const res = await fetch(WEBHOOK_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        event,
        timestamp: new Date().toISOString(),
        ...metadata,
      }),
    });
    if (res.ok) {
      console.log(`[pmtiles-webhook] Rebuild triggered (event: ${event}, HTTP ${res.status})`);
      return { ok: true };
    }
    if (res.status === 409) {
      console.log(`[pmtiles-webhook] Rebuild already running (event: ${event})`);
      return { ok: true, alreadyRunning: true };
    }
    console.warn(`[pmtiles-webhook] Webhook returned HTTP ${res.status}`);
    return { ok: false };
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    console.warn(`[pmtiles-webhook] Failed: ${msg}`);
    return { ok: false };
  }
}
