/* ============================================
   API — shared fetch wrapper, exposes window.API
   ============================================ */
window.API = (function () {
  const TOKEN_KEY = "ors_token";
  const TASK_KEY = "current_task_id";

  function getToken() { return localStorage.getItem(TOKEN_KEY); }
  function setToken(t) { localStorage.setItem(TOKEN_KEY, t); }
  function clearToken() { localStorage.removeItem(TOKEN_KEY); }

  async function request(method, path, body, opts = {}) {
    const headers = { ...(opts.headers || {}) };
    const isForm = body instanceof FormData;
    if (body && !isForm) headers["Content-Type"] = "application/json";

    const token = getToken();
    if (token) headers["Authorization"] = `Bearer ${token}`;

    const res = await fetch(`/api${path}`, {
      method,
      headers,
      body: isForm ? body : (body ? JSON.stringify(body) : undefined),
    });

    if (res.status === 401 && path !== "/auth/login") {
      clearToken();
      if (window.location.hash !== "#login") {
        window.location.hash = "login";
      }
      throw new Error("Session expired");
    }

    if (!res.ok) {
      let detail = res.statusText;
      try { detail = (await res.json()).detail || detail; } catch (_) {}
      const err = new Error(detail);
      err.status = res.status;
      throw err;
    }
    return res;
  }

  async function login(email, password) {
    const res = await request("POST", "/auth/login", { email, password });
    return res.json();
  }

  async function logout() {
    try { await request("POST", "/auth/logout"); } catch (_) {}
    clearToken();
  }

  async function me() {
    const res = await request("GET", "/auth/me");
    return res.json();
  }

  async function upload(file) {
    const form = new FormData();
    form.append("file", file);
    const res = await request("POST", "/upload", form);
    return res.json();
  }

  async function status(taskId) {
    const res = await request("GET", `/status/${taskId}`);
    return res.json();
  }

  // Returns the raw Response so the caller can consume the SSE stream.
  async function chat(prompt) {
    return request("POST", "/chat", { prompt });
  }

  return {
    TOKEN_KEY, TASK_KEY,
    getToken, setToken, clearToken,
    login, logout, me,
    upload, status, chat,
    request,
  };
})();
