import { msalInstance, loginRequest } from "./msalConfig.js";
import { log, warn, error } from "./logger.js";

export async function initializeAuth() {
  log("Running handleRedirectPromise...");

  return msalInstance.handleRedirectPromise().then((response) => {
    if (response) {
      log("Redirect response received:", response);

      if (response.account) {
        log("Setting active account from redirect:", response.account.username);
        msalInstance.setActiveAccount(response.account);
      }
    } else {
      log("No redirect response (normal page load).");
    }

    const accounts = msalInstance.getAllAccounts();
    log("Existing accounts:", accounts);

    if (accounts.length > 0 && !msalInstance.getActiveAccount()) {
      log("Setting first account as active:", accounts[0].username);
      msalInstance.setActiveAccount(accounts[0]);
    }
  });
}

export async function getToken() {
  const active = msalInstance.getActiveAccount();
  log("Starting token acquisition. Active account:", active);

  try {
    log("Attempting acquireTokenSilent...");
    const result = await msalInstance.acquireTokenSilent({
      ...loginRequest,
      account: active
    });

    log("Silent token success:");
    log("  Expires:", new Date(result.expiresOn).toLocaleString());
    log("  Scopes:", result.scopes);
    log("  Access token (first 20 chars):", result.accessToken.slice(0, 20) + "...");

    return result.accessToken;

  } catch (err) {
    warn("Silent token failed:", err);

    // Only do popup if it truly needs human interaction
    if (err.name === "InteractionRequiredAuthError" ||
        err.errorCode === "interaction_required") {

      log("Interaction required → Launching popup login...");

      const popup = await msalInstance.loginPopup(loginRequest);
      log("Popup login success. Account:", popup.account.username);

      msalInstance.setActiveAccount(popup.account);

      log("Retrying silent acquisition after popup...");
      const refreshed = await msalInstance.acquireTokenSilent({
        ...loginRequest,
        account: popup.account
      });

      log("Post-popup silent token success:");
      log("  Expires:", new Date(refreshed.expiresOn).toLocaleString());
      log("  Access token (first 20 chars):", refreshed.accessToken.slice(0, 20) + "...");

      return refreshed.accessToken;
    }

    error("Unexpected token error:", err);
    throw err;
  }
}
