/* Langfuse Lens — API Client */

export async function request(method, url, body = null) {
  const opts = {
    method,
    headers: {},
  };
  if (body !== null) {
    opts.headers["Content-Type"] = "application/json";
    opts.body = JSON.stringify(body);
  }
  const token = localStorage.getItem("lens_token");
  if (token) {
    opts.headers["Authorization"] = `Bearer ${token}`;
  }
  const res = await fetch(url, opts);
  if (res.status === 401) {
    localStorage.removeItem("lens_token");
    window.location.href = "/login?next=" + encodeURIComponent(window.location.pathname);
    return;
  }
  if (!res.ok) {
    let detail = `HTTP ${res.status}`;
    try {
      const err = await res.json();
      detail = err.detail || err.message || detail;
    } catch {
      detail = await res.text() || detail;
    }
    throw new Error(detail);
  }
  const ct = res.headers.get("content-type") || "";
  if (ct.includes("application/json")) {
    return res.json();
  }
  return res.text();
}

export const api = {
  get:    (url) => request("GET", url),
  post:   (url, body) => request("POST", url, body),
  put:    (url, body) => request("PUT", url, body),
  patch:  (url, body) => request("PATCH", url, body),
  del:    (url) => request("DELETE", url),
};
