import { ConfigService } from "../../configService/index.mjs";
import { EventType, PublicClientApplication } from "@azure/msal-browser";
//#region src/utilities/auth/signInAuthProvider.js
/** @type {import('@azure/msal-browser').PublicClientApplication | null} */
let signInAuthProviderInstance = null;
/** @type {import('@azure/msal-browser').RedirectRequest | null} */
let loginRequestInstance = null;
/** @type {import('@azure/msal-browser').SilentRequest | null} */
let tokenRequestInstance = null;
/** @type {string | null} */
let apiAccessScopeValue = null;
/**
* Initializes the MSAL auth provider and request templates.
* @returns {Promise<void>}
*/
async function initSignInAuthProvider() {
	if (signInAuthProviderInstance) return;
	const PUBLIC_URL = new URL(import.meta.env.BASE_URL || "/", window.location.origin).href.replace(/\/$/, "");
	const REDIRECT_URL_BASE = ConfigService.config.USE_AAD_REDIRECT ? ConfigService.config.UNITY_URL : PUBLIC_URL;
	if (!ConfigService.config.MSAL_TENANT) throw new Error("MSAL_TENANT not configured");
	if (!ConfigService.config.MSAL_CLIENT_ID) throw new Error("MSAL_CLIENT_ID not configured");
	const tenant = ConfigService.config.MSAL_TENANT;
	const currentPath = window.location.pathname;
	const searchParams = new URLSearchParams(window.location.search);
	let domainHint = searchParams.get("domain_hint");
	if (currentPath === "/sso/entra") domainHint = "entra";
	if (currentPath === "/sso/entra") {
		domainHint = "entra";
		window.history.replaceState(null, "", "/");
	}
	const idTokenHint = searchParams.get("id_token_hint");
	const signInPolicy = ConfigService.config.SIGN_IN_POLICY;
	const applicationID = ConfigService.config.MSAL_CLIENT_ID;
	const reactRedirectUri = `${REDIRECT_URL_BASE}/${ConfigService.config.USE_AAD_REDIRECT ? "aad_redirect" : "aad_callback"}`;
	const tenantSubdomain = tenant.split(".")[0];
	const signInAuthority = `${`https://${tenantSubdomain}.b2clogin.com/`}${tenant}/${signInPolicy}`;
	apiAccessScopeValue = `https://${tenant}/${ConfigService.config.MSAL_API_ACCESS_SCOPE}`;
	const ua = window.navigator.userAgent;
	const msie = ua.indexOf("MSIE ");
	const msie11 = ua.indexOf("Trident/");
	const msedge = ua.indexOf("Edge/");
	const firefox = ua.indexOf("Firefox");
	const isIE = msie > 0 || msie11 > 0;
	const isEdge = msedge > 0;
	const isFirefox = firefox > 0;
	signInAuthProviderInstance = new PublicClientApplication({
		auth: {
			authority: signInAuthority,
			knownAuthorities: [`${tenantSubdomain}.b2clogin.com`],
			clientId: applicationID,
			redirectUri: reactRedirectUri,
			postLogoutRedirectUri: PUBLIC_URL + "/",
			navigateToLoginRequestUrl: false
		},
		cache: {
			cacheLocation: "sessionStorage",
			storeAuthStateInCookie: isIE || isEdge || isFirefox
		},
		system: { allowRedirectInIframe: true }
	});
	await signInAuthProviderInstance.initialize();
	if (!signInAuthProviderInstance.getActiveAccount() && signInAuthProviderInstance.getAllAccounts().length > 0) signInAuthProviderInstance.setActiveAccount(signInAuthProviderInstance.getAllAccounts()[0]);
	const activeAccount = signInAuthProviderInstance.getActiveAccount();
	if (activeAccount && !domainHint) {
		const idp = activeAccount.idTokenClaims?.idp;
		if (idp && idp.includes("login.microsoftonline.com")) domainHint = "entra";
	}
	signInAuthProviderInstance.addEventCallback((event) => {
		if (event.eventType === EventType.LOGIN_SUCCESS && event.payload.account) {
			const account = event.payload.account;
			signInAuthProviderInstance.setActiveAccount(account);
		}
	});
	tokenRequestInstance = { scopes: [apiAccessScopeValue] };
	loginRequestInstance = {
		scopes: [
			apiAccessScopeValue,
			"openid",
			"offline_access"
		],
		state: `${PUBLIC_URL}/aad_callback`,
		extraQueryParameters: {
			...idTokenHint && {
				id_token_hint: idTokenHint,
				flow: "redeem"
			},
			...domainHint && !idTokenHint && { domain_hint: "entra" }
		}
	};
}
const getSignInAuthProvider = () => {
	if (!signInAuthProviderInstance) throw new Error("signInAuthProvider is not initialized. Call initSignInAuthProvider first.");
	return signInAuthProviderInstance;
};
/**
* @returns {import('@azure/msal-browser').RedirectRequest}
*/
const getLoginRequest = () => {
	if (!loginRequestInstance) throw new Error("loginRequest is not initialized. Call initSignInAuthProvider first.");
	return loginRequestInstance;
};
/**
* @returns {import('@azure/msal-browser').SilentRequest}
*/
const getTokenRequest = () => {
	if (!tokenRequestInstance) throw new Error("tokenRequest is not initialized. Call initSignInAuthProvider first.");
	return tokenRequestInstance;
};
const getApiAccessScope = () => {
	if (!apiAccessScopeValue) throw new Error("apiAccessScope is not initialized. Call initSignInAuthProvider first.");
	return apiAccessScopeValue;
};
//#endregion
export { getApiAccessScope, getLoginRequest, getSignInAuthProvider, getTokenRequest, initSignInAuthProvider };

//# sourceMappingURL=signInAuthProvider.mjs.map