/* auth.jsx — prihlásenie cez Microsoft (MSAL.js) a získavanie Graph tokenov.
   Vystavuje window.HELPDESK_AUTH = { login(), logout(), getToken(), getAccount() }.
   Používa Authorization Code + PKCE (MSAL to robí automaticky pre "spa" redirectUri).
*/
(function () {
  "use strict";

  const GRAPH_SCOPES = [
    "https://graph.microsoft.com/User.Read",
    "https://graph.microsoft.com/Sites.Selected",
  ];

  const cfg = window.HELPDESK_CONFIG;

  const msalInstance = new msal.PublicClientApplication({
    auth: {
      clientId: cfg.CLIENT_ID,
      authority: "https://login.microsoftonline.com/" + cfg.TENANT_ID,
      // Zámerne len origin (bez cesty k stránke) — Cloudflare Pages automaticky odstraňuje
      // ".html" z URL, takže cesta k stránke sa mení podľa toho, ako presne user na appku prišiel.
      // Koreňová URL je stabilná a presne zodpovedá Redirect URI zaregistrovanému v Entra ID.
      redirectUri: window.location.origin,
    },
    cache: {
      // sessionStorage = odporúčanie MSAL pre SPA (menej medzi-tabového pomiešania tokenov
      // ako localStorage). Štopka v details.jsx zámerne používa localStorage — je to iný,
      // nesúvisiaci mechanizmus (prežitie štopky cez reload, nie MSAL token cache).
      cacheLocation: "sessionStorage",
      storeAuthStateInCookie: false,
    },
  });

  let ready = null;
  function ensureReady() {
    if (!ready) ready = msalInstance.initialize();
    return ready;
  }

  function pickActiveAccount() {
    const accounts = msalInstance.getAllAccounts();
    if (accounts.length === 0) return null;
    msalInstance.setActiveAccount(accounts[0]);
    return accounts[0];
  }

  async function login() {
    await ensureReady();
    const result = await msalInstance.loginPopup({ scopes: GRAPH_SCOPES });
    msalInstance.setActiveAccount(result.account);
    return result.account;
  }

  function logout() {
    const account = msalInstance.getActiveAccount();
    return msalInstance.logoutPopup({ account });
  }

  function getAccount() {
    return msalInstance.getActiveAccount() || pickActiveAccount();
  }

  async function getToken() {
    await ensureReady();
    const account = getAccount();
    if (!account) throw new Error("Nie si prihlásený.");
    try {
      const res = await msalInstance.acquireTokenSilent({ scopes: GRAPH_SCOPES, account });
      return res.accessToken;
    } catch (err) {
      // Tiché obnovenie zlyhalo (napr. vypršaný refresh token, zmena hesla,
      // podmienkový prístup) — skús interaktívne prihlásenie namiesto tvrdej chyby.
      if (err instanceof msal.InteractionRequiredAuthError) {
        const res = await msalInstance.acquireTokenPopup({ scopes: GRAPH_SCOPES, account });
        return res.accessToken;
      }
      throw err;
    }
  }

  window.HELPDESK_AUTH = { login, logout, getToken, getAccount, ensureReady };
})();
