// api.jsx — Liten klient mot /api (Azure Functions).
// Exponeras som window.API. Hanterar JWT-token i sessionStorage.
(function () {
  const TOKEN_KEY = 'sint_token';

  function token()      { try { return sessionStorage.getItem(TOKEN_KEY); } catch (e) { return null; } }
  function setToken(t)  { try { sessionStorage.setItem(TOKEN_KEY, t); } catch (e) {} }
  function role()       { try { return sessionStorage.getItem('sint_role'); } catch (e) { return null; } }
  function setRole(r)   { try { sessionStorage.setItem('sint_role', r || ''); } catch (e) {} }
  function clearToken() { try { sessionStorage.removeItem(TOKEN_KEY); sessionStorage.removeItem('sint_role'); } catch (e) {} }
  function isAuthed()   { return !!token(); }

  function authHeaders() {
    const t = token();
    // Egen header — SWA reserverar 'Authorization' för sin egen inloggning
    return t ? { 'X-Sint-Auth': t } : {};
  }

  async function handle(res, authed) {
    if (res.status === 204) return null;
    let body = null;
    const text = await res.text();
    if (text) { try { body = JSON.parse(text); } catch (e) { body = text; } }
    if (!res.ok) {
      // Inloggad förfrågan som nekas → sessionen har gått ut. Logga ut + be om ny inloggning.
      if (res.status === 401 && authed) {
        clearToken();
        try { sessionStorage.removeItem('sint_admin'); } catch (e) {}
        window.dispatchEvent(new CustomEvent('sint-session-expired'));
      }
      // 403 = inloggad men saknar behörighet — låt anroparen hantera felet
      const err = new Error((body && body.error) || ('HTTP ' + res.status));
      err.status = res.status;
      err.body = body;
      throw err;
    }
    return body;
  }

  function buildPath(path, query) {
    let url = '/api/' + path;
    if (query && typeof query === 'object') {
      const qs = Object.entries(query)
        .filter(([, v]) => v !== undefined && v !== null && v !== '')
        .map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(v))
        .join('&');
      if (qs) url += '?' + qs;
    }
    return url;
  }

  async function get(path, query) {
    const authed = !!token();
    const res = await fetch(buildPath(path, query), { headers: authHeaders() });
    return handle(res, authed);
  }

  async function post(path, body) {
    const authed = !!token();
    const res = await fetch(buildPath(path), {
      method: 'POST',
      headers: Object.assign({ 'Content-Type': 'application/json' }, authHeaders()),
      body: JSON.stringify(body || {}),
    });
    return handle(res, authed);
  }

  async function patch(path, body) {
    const authed = !!token();
    const res = await fetch(buildPath(path), {
      method: 'PATCH',
      headers: Object.assign({ 'Content-Type': 'application/json' }, authHeaders()),
      body: JSON.stringify(body || {}),
    });
    return handle(res, authed);
  }

  async function del(path, query) {
    const authed = !!token();
    const res = await fetch(buildPath(path, query), { method: 'DELETE', headers: authHeaders() });
    return handle(res, authed);
  }

  window.API = { token, setToken, role, setRole, clearToken, isAuthed, get, post, patch, del };
})();
