/**
 * Microsoft Authentication Library (MSAL) Configuration
 *
 * Configures MSAL for Azure AD authentication with PKCE flow.
 * PKCE is automatically enabled for browser-based SPAs.
 */

import { LogLevel } from '@azure/msal-browser';
import type { Configuration } from '@azure/msal-browser';

/**
 * MSAL Configuration
 *
 * Documentation: https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md
 */
export const msalConfig: Configuration = {
  auth: {
    clientId: import.meta.env.VITE_AZURE_CLIENT_ID || '',
    authority: import.meta.env.VITE_AZURE_AUTHORITY || '',
    redirectUri: import.meta.env.VITE_AZURE_REDIRECT_URI || window.location.origin,
    postLogoutRedirectUri: import.meta.env.VITE_AZURE_REDIRECT_URI || window.location.origin,
    navigateToLoginRequestUrl: false, // We handle navigation ourselves
  },
  cache: {
    cacheLocation: 'sessionStorage', // More secure than localStorage
    storeAuthStateInCookie: false, // Set to true for IE 11 or Edge
  },
  system: {
    loggerOptions: {
      loggerCallback: (level: LogLevel, message: string, containsPii: boolean) => {
        if (containsPii) {
          return;
        }
        switch (level) {
          case LogLevel.Error:
            console.error('[MSAL]', message);
            return;
          case LogLevel.Info:
            console.info('[MSAL]', message);
            return;
          case LogLevel.Verbose:
            console.debug('[MSAL]', message);
            return;
          case LogLevel.Warning:
            console.warn('[MSAL]', message);
            return;
        }
      },
      logLevel: import.meta.env.DEV ? LogLevel.Info : LogLevel.Error,
      piiLoggingEnabled: false,
    },
    windowHashTimeout: 60000,
    iframeHashTimeout: 6000,
    loadFrameTimeout: 0,
  },
};

/**
 * Scopes for login request
 *
 * openid: Required for OIDC
 * profile: Get user's display name
 * email: Get user's email address
 */
export const loginRequest = {
  scopes: ['openid', 'profile', 'email'],
};

/**
 * Scopes for silent token acquisition
 */
export const tokenRequest = {
  scopes: ['openid', 'profile', 'email'],
};

/**
 * Validate MSAL configuration
 *
 * Throws error if required environment variables are missing
 */
export function validateMsalConfig(): void {
  const clientId = import.meta.env.VITE_AZURE_CLIENT_ID;
  const authority = import.meta.env.VITE_AZURE_AUTHORITY;
  const redirectUri = import.meta.env.VITE_AZURE_REDIRECT_URI;

  if (!clientId) {
    throw new Error('VITE_AZURE_CLIENT_ID is not configured');
  }

  if (!authority) {
    throw new Error('VITE_AZURE_AUTHORITY is not configured');
  }

  if (!redirectUri) {
    console.warn('VITE_AZURE_REDIRECT_URI is not configured, using window.location.origin');
  }

  console.log('[MSAL] Configuration validated successfully');
}
