import "server-only";

// Trigger un rebuild GitLab du site vitrine (`missioflow-site`, Astro statique
// sur https://missioflow.fr) après une modification réussie d'un plan.
//
// Pourquoi : le vitrine est SSG, le HTML est figé au build. Sans ce trigger,
// éditer un plan dans sysop laisse missioflow.fr/tarifs sur l'ancien wording
// jusqu'au prochain push manuel. Cf. mf_ask #70.
//
// Pas de cooldown / debounce ici : si l'admin enchaîne 5 PATCHs en 30s, on
// déclenche 5 builds. GitLab gère bien (`interruptible: true` côté pipeline
// vitrine = la nouvelle pipeline annule la précédente).
//
// Fire-and-forget côté caller — ne JAMAIS bloquer la réponse PATCH sur ce
// fetch : si GitLab est down ou le token absent, l'admin doit quand même voir
// son UPDATE confirmé.

const VITRINE_PROJECT_PATH = "Taaazzz-prog%2Fmissioflow-site";

export async function triggerVitrineRebuild(planCode: string): Promise<void> {
  const token = process.env.MISSIOFLOW_SITE_REBUILD_TRIGGER_TOKEN;
  const baseUrl = process.env.GITLAB_BASE_URL ?? "http://192.168.1.153";
  if (!token) {
    console.warn(
      "[vitrine-rebuild] MISSIOFLOW_SITE_REBUILD_TRIGGER_TOKEN absent — skip trigger",
    );
    return;
  }

  const url = `${baseUrl}/api/v4/projects/${VITRINE_PROJECT_PATH}/trigger/pipeline`;
  const body = new URLSearchParams({
    ref: "main",
    token,
    "variables[TRIGGERED_BY]": "panel-plan-update",
    "variables[TRIGGERED_PLAN]": planCode,
  });

  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body,
  });

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