import { useCardState } from "../../elements/contexts/index.js";
import { deriveInitialStep } from "./deriveInitialStep.js";
import React, { useCallback } from "react";
import { jsx } from "@emotion/react/jsx-runtime";
import { useSession, useUser } from "@clerk/shared/react/index";

//#region src/components/ConfigureSSO/ConfigureSSOContext.tsx
const ConfigureSSOContext = React.createContext(null);
ConfigureSSOContext.displayName = "ConfigureSSOContext";
const ConfigureSSOProvider = ({ enterpriseConnection, hasSuccessfulTestRun, contentRef, createEnterpriseConnection: createEnterpriseConnectionApi, updateEnterpriseConnection, deleteEnterpriseConnection, children }) => {
	const [provider, setProvider] = React.useState(enterpriseConnection?.provider);
	const { session } = useSession();
	const { user } = useUser();
	const card = useCardState();
	const isDomainTakenByOtherOrg = checkDomainTakenByOtherOrg(user, session, enterpriseConnection);
	const initialStepId = deriveInitialStep(enterpriseConnection, {
		isDomainTakenByOtherOrg,
		hasSuccessfulTestRun
	});
	const createEnterpriseConnection = useCallback(async (provider$1, primaryEmailAddress) => {
		const emailDomain = primaryEmailAddress?.emailAddress.split("@")[1];
		const organizationId = session?.lastActiveOrganizationId ?? null;
		if (!emailDomain) return;
		card.setLoading();
		try {
			await createEnterpriseConnectionApi({
				provider: provider$1,
				name: emailDomain,
				organizationId
			});
		} finally {
			card.setIdle();
		}
	}, [
		card,
		session,
		createEnterpriseConnectionApi
	]);
	const value = React.useMemo(() => ({
		provider,
		contentRef,
		setProvider,
		initialStepId,
		enterpriseConnection,
		isDomainTakenByOtherOrg,
		createEnterpriseConnection,
		updateEnterpriseConnection,
		deleteEnterpriseConnection
	}), [
		provider,
		contentRef,
		initialStepId,
		enterpriseConnection,
		createEnterpriseConnection,
		updateEnterpriseConnection,
		deleteEnterpriseConnection,
		isDomainTakenByOtherOrg
	]);
	return /* @__PURE__ */ jsx(ConfigureSSOContext.Provider, {
		value,
		children
	});
};
const useConfigureSSO = () => {
	const ctx = React.useContext(ConfigureSSOContext);
	if (!ctx) throw new Error("useConfigureSSO called outside <ConfigureSSOProvider>.");
	return ctx;
};
/**
* Determines if the user's domain is already wired to an enterprise connection that
* doesn't belong to the org they're currently configuring
*/
const checkDomainTakenByOtherOrg = (user, session, enterpriseConnection) => {
	const isVerified = (user?.primaryEmailAddress ?? user?.emailAddresses?.find((e) => e.verification.status !== "verified"))?.verification.status === "verified";
	const activeOrganizationId = session?.lastActiveOrganizationId ?? null;
	return Boolean(isVerified && enterpriseConnection && enterpriseConnection.organizationId !== activeOrganizationId);
};

//#endregion
export { ConfigureSSOProvider, useConfigureSSO };
//# sourceMappingURL=ConfigureSSOContext.js.map