// 统一 JSON fetch 封装:注入 Bearer token,解析 JSON/文本,非 2xx 抛带 status 的 Error。
// (login / create_user / SSE / 文件下载 因 header / 流式 / blob 特殊,仍各自手写 fetch)
import { state, LS_TOKEN } from "./state.js";

// 滑动续签:后端在临期 token 的响应里带 X-Refreshed-Token(见 web/auth.py),
// 这里无感换掉本地 token → 活跃用户永不因 TTL 到期被踢回登录页。
export function absorbRefreshedToken(r) {
  const fresh = r.headers.get("X-Refreshed-Token");
  if (fresh && fresh !== state.token) {
    state.token = fresh;
    localStorage.setItem(LS_TOKEN, fresh);
  }
}

export async function api(method, path, body) {
  const opts = { method, headers: {} };
  if (state.token) opts.headers["Authorization"] = "Bearer " + state.token;
  if (body !== undefined) {
    opts.headers["Content-Type"] = "application/json";
    opts.body = JSON.stringify(body);
  }
  const r = await fetch(path, opts);
  absorbRefreshedToken(r);
  let data = null;
  const ct = r.headers.get("content-type") || "";
  if (ct.includes("application/json")) {
    try { data = await r.json(); } catch (e) {}
  } else {
    data = await r.text();
  }
  if (!r.ok) {
    const msg = (data && data.detail) || data || (r.status + " " + r.statusText);
    const err = new Error(typeof msg === "string" ? msg : JSON.stringify(msg));
    err.status = r.status;
    throw err;
  }
  return data;
}
