"use strict";
async function netbox_tag_id_print(ctrl) {
    // 1) récupère la valeur dans l'input voisin
    const id = ctrl.dataset.cfId
    const value = (ctrl.dataset?.value || 
        ctrl.querySelector('input')?.value || 
        '').trim();
    // const input = ctrl.querySelector('input');
    // const value = (input && input.value || '').trim();
    if (!value) {
      alert("Aucune valeur à imprimer.");
      return;
    }

    // 2) construit l’URL GET /plugins/netbox_tag_id/print_cb?...
    //const params = new URLSearchParams({ value, pagesize: "10x8cm" });
    const params = new URLSearchParams({value});
    const url = `/plugins/netbox_tag_id/print_cb/${id}?${params.toString()}`;

    // 3) appel (GET, pas de CSRF)
    const resp  = await fetch(url, { method: "GET", credentials: "same-origin" });
    const data  = await resp.json().catch(() => null);

    // 4) feedback
    if (!resp.ok || !data) {
      alert(`Erreur HTTP ${resp.status} ${resp.statusText}`);
      return;
    }
    if (data.code === 0 || data.ok === true) {
      alert("Impression envoyée ✅");
    } else {
      const out = Array.isArray(data.output) ? data.output.join("\n") : String(data.output || "");
      alert(`Erreur d'impression (code ${data.code})\n${out}`);
    }
}

async function netbox_tag_id_generate(ctrl) {
  console.log(ctrl, ctrl.dataset.cfId);
  const id = ctrl.dataset.cfId;
  const response = await fetch(`/plugins/netbox_tag_id/generate/${id}`);
  const value = await response.text();
  const input = ctrl.querySelector('input');
  input.value = value;
}
