// ── Raw HTTP wrappers ─────────────────────────────────────────────────────────
// These functions only perform fetch() calls and return the raw Response or
// parsed JSON. No state mutations, no DOM access.

export async function apiFetchConfig(team) {
  const token = localStorage.getItem("authToken");
  const headers = token ? { Authorization: `Bearer ${token}` } : {};
  const res = await fetch(`/api/config?team=${encodeURIComponent(team)}`, {
    headers,
    cache: "no-store",
  });
  if (!res.ok) throw new Error("config_fetch_failed");
  return res.json();
}

/** Returns the raw Response so the caller can inspect status codes (410, etc.). */
export async function apiFetchGrid(seed) {
  const token = localStorage.getItem("authToken");
  const headers = token ? { Authorization: `Bearer ${token}` } : {};
  return fetch(`/api/grid/${encodeURIComponent(seed)}`, {
    headers,
    cache: "no-store",
  });
}

/** Returns the raw Response so the caller can inspect status codes (409, 410, etc.). */
export async function apiRevealCell(seed, x, y, team) {
  const token = localStorage.getItem("authToken");
  return fetch("/api/cell/reveal", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: JSON.stringify({ seed, x, y, team }),
  });
}

export async function apiLogin(username, password) {
  return fetch("/api/auth/login", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, password }),
  });
}

export async function apiRegister(username, password, team) {
  return fetch("/api/auth/register", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ username, password, team }),
  });
}

export async function apiGetMe(token) {
  return fetch("/api/auth/me", {
    headers: { Authorization: `Bearer ${token}` },
  });
}

export async function apiFetchEconScores() {
  const res = await fetch("/api/econ-scores");
  if (!res.ok) throw new Error("econ_scores_fetch_failed");
  return res.json();
}

export async function apiTickEconScores(seed, blue, red) {
  const res = await fetch("/api/econ-scores/tick", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ seed, blue, red }),
  });
  if (!res.ok) throw new Error("econ_tick_failed");
  return res.json();
}

export async function apiFetchElementBonus() {
  const res = await fetch("/api/element-bonus");
  if (!res.ok) throw new Error("element_bonus_fetch_failed");
  return res.json();
}

export async function apiTickElementBonus(seed, blue, red) {
  const res = await fetch("/api/element-bonus/tick", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ seed, blue, red }),
  });
  if (!res.ok) throw new Error("element_bonus_tick_failed");
  return res.json();
}

export async function apiFetchDbInfo() {
  const res = await fetch("/api/db-info");
  if (!res.ok) throw new Error("db_info_fetch_failed");
  return res.json();
}

export async function apiFetchVictoryPoints() {
  const res = await fetch("/api/victory-points");
  if (!res.ok) throw new Error("vp_fetch_failed");
  return res.json();
}

export async function apiFetchPlayerCounts() {
  const res = await fetch("/api/auth/player-counts");
  if (!res.ok) throw new Error("player_counts_fetch_failed");
  return res.json();
}

export async function apiFetchActivePlayers() {
  const res = await fetch("/api/active-players");
  if (!res.ok) throw new Error("active_players_fetch_failed");
  return res.json();
}

export async function apiFetchActivePlayerNames() {
  const res = await fetch("/api/active-players/names");
  if (!res.ok) throw new Error("active_player_names_fetch_failed");
  return res.json();
}

export async function apiFetchMilitaryDeductions() {
  const res = await fetch("/api/military-deductions");
  if (!res.ok) throw new Error("military_deductions_fetch_failed");
  return res.json();
}

export async function apiMilitaryAttack(seed, x, y) {
  const token = localStorage.getItem("authToken");
  const res = await fetch("/api/military/attack", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: JSON.stringify({ seed, x, y }),
  });
  return res; // caller inspects status
}

export async function apiFetchCellAttackCount(x, y) {
  const res = await fetch(`/api/cell/attacks?x=${x}&y=${y}`);
  if (!res.ok) throw new Error("cell_attacks_fetch_failed");
  return res.json();
}

/** Returns the raw Response so the caller can inspect status codes. */
export async function apiCaptureCell(seed, x, y) {
  const token = localStorage.getItem("authToken");
  return fetch("/api/cell/capture", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: JSON.stringify({ seed, x, y }),
  });
}
