import { ConfigService } from "../../configService/index.mjs";
import { TenantTypeEnums } from "../../enums/unitySystemEnums.mjs";
import { useTenantStore } from "../../stores/tenantStore.mjs";
import { UserDispatchContext } from "../auth/internal.mjs";
import { useUser } from "../auth/useUser.mjs";
import { storeTenant } from "../storage/UnitySessionStorage.mjs";
import { useApiQuery } from "../useApiQuery.mjs";
import { MenuProvider } from "../menus/MenuProvider.mjs";
import { LoadingIndicator } from "../../UI/loading/LoadingIndicator/LoadingIndicator.mjs";
import { TenantContext } from "./tenantContext.mjs";
import { useProductsStore } from "../../stores/productsStore.mjs";
import { c } from "react-compiler-runtime";
import React, { Suspense, lazy, useCallback, useContext, useEffect, useMemo } from "react";
import { useAccount } from "@azure/msal-react";
//#region src/utilities/tenant/TenantProvider.jsx
const TenantAccessDialog = lazy(() => import("./TenantAccessDialog.mjs").then((m) => ({ default: m.TenantAccessDialog })));
const UdpDialog = lazy(() => import("../../UI/fluent-web-components/UdpDialog.mjs").then((m) => ({ default: m.UdpDialog })));
const useTenantStoreSync = (activeTenant) => {
	const $ = c(9);
	const setCurrentTenant = useTenantStore(_temp);
	let t0;
	if ($[0] !== activeTenant || $[1] !== setCurrentTenant) {
		t0 = () => {
			if (!activeTenant?.tenantId) return;
			const current = useTenantStore.getState().currentTenant;
			const theme = activeTenant.theme ?? null;
			const name = activeTenant.tenantName ?? null;
			const tenantType = activeTenant.tenantType;
			if (current?.tenantId === activeTenant.tenantId && current?.tenantType === tenantType && (current?.name ?? null) === name && (current?.theme ?? null) === theme) return;
			setCurrentTenant({
				tenantId: activeTenant.tenantId,
				name,
				tenantType,
				theme
			});
		};
		$[0] = activeTenant;
		$[1] = setCurrentTenant;
		$[2] = t0;
	} else t0 = $[2];
	const t1 = activeTenant?.tenantId;
	const t2 = activeTenant?.tenantName;
	const t3 = activeTenant?.tenantType;
	const t4 = activeTenant?.theme;
	let t5;
	if ($[3] !== setCurrentTenant || $[4] !== t1 || $[5] !== t2 || $[6] !== t3 || $[7] !== t4) {
		t5 = [
			t1,
			t2,
			t3,
			t4,
			setCurrentTenant
		];
		$[3] = setCurrentTenant;
		$[4] = t1;
		$[5] = t2;
		$[6] = t3;
		$[7] = t4;
		$[8] = t5;
	} else t5 = $[8];
	useEffect(t0, t5);
};
const TenantProvider = ({ children }) => {
	const user = useUser();
	const activeAccount = useAccount();
	const { changeTenant } = useContext(UserDispatchContext);
	const { data: tenants, isLoading: tenantsLoading, refetch: refresh } = useApiQuery(ConfigService.securityV2ApiUrl, `user/tenants?productId=${ConfigService.config.UNITY_PRODUCT_ID}`, { skipTenantHeader: true }, { enabled: !!activeAccount?.idTokenClaims });
	const { data: selectedProduct, isLoading: productsLoading } = useApiQuery(ConfigService.tenantV2ApiUrl, `product/${ConfigService.config.UNITY_PRODUCT_ID}`, { skipTenantHeader: true }, { enabled: !!activeAccount?.idToken });
	const hasTenantsData = Array.isArray(tenants);
	const userHasLoaded = user && user.statusCode !== void 0;
	const activeTenant = user?.currentTenantId && hasTenantsData ? tenants.find((t) => t.tenantId === user.currentTenantId) ?? null : null;
	const isProductTenant = activeTenant?.tenantType === TenantTypeEnums.Product;
	useTenantStoreSync(activeTenant);
	if (selectedProduct?.isUnityDefault && activeTenant?.tenantId) useProductsStore.getState().fetchProducts(activeTenant.tenantId);
	const handleTenantChange = useCallback((tenant) => {
		if (!tenant) return;
		storeTenant(tenant.tenantId);
		changeTenant(tenant.tenantId);
	}, [changeTenant]);
	const contextValue = useMemo(() => ({
		tenantsList: tenants ?? null,
		filteredTenantsList: tenants ?? null,
		activeTenant,
		isProductTenant,
		refresh
	}), [
		tenants,
		activeTenant,
		isProductTenant,
		refresh
	]);
	if (Boolean(activeAccount) && (tenantsLoading && !tenants || productsLoading && !selectedProduct)) return /* @__PURE__ */ React.createElement(LoadingIndicator, null);
	const noTenantsAvailable = hasTenantsData && tenants.length === 0 && userHasLoaded;
	const currentTenantAllowed = hasTenantsData ? tenants.some((t_0) => t_0.tenantId === user?.currentTenantId) : false;
	const shouldShowTenantMismatchDialog = userHasLoaded && hasTenantsData && !noTenantsAvailable && !currentTenantAllowed;
	if (noTenantsAvailable) return /* @__PURE__ */ React.createElement(Suspense, { fallback: /* @__PURE__ */ React.createElement(LoadingIndicator, null) }, /* @__PURE__ */ React.createElement(UdpDialog, {
		open: true,
		dialogTitle: "No Access",
		type: "alert",
		showHeaderCloseButton: false
	}, "Your user does not have access to any tenants for this product. Please contact your support team."));
	return /* @__PURE__ */ React.createElement(TenantContext.Provider, { value: contextValue }, /* @__PURE__ */ React.createElement(MenuProvider, null, shouldShowTenantMismatchDialog && /* @__PURE__ */ React.createElement(Suspense, { fallback: /* @__PURE__ */ React.createElement(LoadingIndicator, null) }, /* @__PURE__ */ React.createElement(TenantAccessDialog, {
		open: shouldShowTenantMismatchDialog,
		tenants,
		onTenantChange: handleTenantChange,
		productName: selectedProduct?.productName
	})), !shouldShowTenantMismatchDialog && children));
};
function _temp(state) {
	return state.setCurrentTenant;
}
//#endregion
export { TenantProvider };

//# sourceMappingURL=TenantProvider.mjs.map