import { apiUrl } from "./session.js";

let promoCsrf = "";

async function ensurePromoCsrf() {
  if (promoCsrf) return;
  const r = await fetch(apiUrl("user_me.php"), { credentials: "include" });
  const data = await r.json().catch(() => ({}));
  if (typeof data.csrfToken === "string" && data.csrfToken.length > 0) {
    promoCsrf = data.csrfToken;
  }
}

export async function postUserPromoRedeem(code) {
  await ensurePromoCsrf();
  const headers = { "Content-Type": "application/json" };
  if (promoCsrf) headers["X-CSRF-Token"] = promoCsrf;
  const r = await fetch(apiUrl("user_promo_redeem.php"), {
    method: "POST",
    credentials: "include",
    headers,
    body: JSON.stringify({ code: String(code || "").trim() }),
  });
  const data = await r.json().catch(() => ({}));
  return { ok: r.ok && data.ok === true, status: r.status, data };
}
