/* api.jsx: talking to cc_api from the browser.
 *  - Auth: Catalyst hosted login, new browser SDK (window.zcAuthReady in index.html).
 *  - Cross-domain from Slate: Authorization: Zoho-oauthtoken <generateAuthToken('functions')>.
 *  - X-Club-Id carries the club the user is acting in (the club switcher).
 * Public routes (org page, club search, "club not listed") are called without a token.
 */
(function () {
  const CFG = window.CLUBCRAFT;
  const sameOrigin = () => window.location.origin === CFG.functionOrigin;
  let tok = null;

  async function authHeader() {
    if (sameOrigin()) return {};
    if (!tok || tok.expiresAt < Date.now() + 60000) {
      const zc = await window.zcAuthReady;
      const t = await zc.generateAuthToken("functions");
      tok = { value: t.access_token, expiresAt: Date.now() + Number(t.expires_in_sec || t.expires_in || 3600) * 1000 };
    }
    return { Authorization: "Zoho-oauthtoken " + tok.value };
  }

  class ApiError extends Error {
    constructor(status, data) { super((data && data.error) || "HTTP " + status); this.status = status; this.data = data || {}; }
  }

  // call(method, path, body, { club, anon })
  async function call(method, path, body, opts) {
    const o = opts || {};
    const base = sameOrigin() ? CFG.functionPath : CFG.functionOrigin + CFG.functionPath;
    const headers = { "Content-Type": "application/json", ...(o.anon ? {} : await authHeader()) };
    if (o.club) headers["X-Club-Id"] = o.club;
    const r = await fetch(base + path, { method, headers, body: body ? JSON.stringify(body) : undefined });
    const data = await r.json().catch(() => ({}));
    if (!r.ok) throw new ApiError(r.status, data);
    // The club's country, currency, zone and language arrive with the club: every screen formats through CCIntl (docs/internationalisation.md).
    if (method === "GET" && /^\/club(\?|$)/.test(path) && data && data.club && data.club.region && window.CCIntl) window.CCIntl.set(data.club.region);
    if (method === "GET" && /^\/club(\?|$)/.test(path) && data && data.me && window.CCIntl) window.CCIntl.setSecond(data.me.secondZone);
    if (path === "/club/region" && data && data.region && window.CCIntl) window.CCIntl.set(data.region);
    return data;
  }

  async function isSignedIn() {
    const zc = await window.zcAuthReady;
    // Documented to return false when signed out; @zcatalyst/auth 1.0.0 throws a 401 instead.
    return zc.isUserAuthenticated().then((u) => !!u).catch((e) => {
      if (e && (e.statusCode === 401 || /401/.test(e.code || ""))) return false;
      throw e;
    });
  }

  // Slate's hosted login rejects redirect_url, so link to the bare pages (they return to the app root).
  const signIn = () => window.location.assign("/__catalyst/auth/login");
  const signUp = () => window.location.assign("/__catalyst/auth/signup");
  async function signOut() {
    tok = null;
    const zc = await window.zcAuthReady;
    return zc.signOut(window.location.origin + window.location.pathname);
  }

  window.ClubcraftApi = { call, isSignedIn, signIn, signUp, signOut, ApiError };
})();
