import { ConfigService } from "../configService/index.mjs";
import { apiMutate } from "../utilities/useAxiosMutate.mjs";
import { useEffect } from "react";
//#region src/hooks/useOutlook.js
const useOutlook = (callbackUri, onLogin) => {
	const invalidateUserSession = async () => {
		try {
			localStorage.removeItem("outlookAccessToken");
		} catch (error) {
			console.error("Error removing accessToken:", error);
		}
		try {
			localStorage.removeItem("outlookRefreshToken");
		} catch (error) {
			console.error("Error removing refreshToken:", error);
		}
		try {
			localStorage.removeItem("outlookExpiresAt");
		} catch (error) {
			console.error("Error removing expiresAt:", error);
		}
	};
	const getAccessToken = async () => {
		let accessToken = localStorage.getItem("outlookAccessToken");
		if (!accessToken) throw new Error("No access token found");
		const expiresAt = localStorage.getItem("outlookExpiresAt");
		if (expiresAt && !isBeforeCurrentTime(expiresAt)) return accessToken;
		const refreshToken = localStorage.getItem("outlookRefreshToken");
		if (!refreshToken) throw new Error("No refresh token found");
		try {
			if (ConfigService.integrationV2ApiUrl === void 0) throw new Error("REACT_APP_INTEGRATION_V2_API_BASE is undefined");
			const data = (await apiMutate(ConfigService.integrationV2ApiUrl, `OutlookIntegrationAccessToken/getAccessToken`, {
				method: "post",
				data: {
					option: "refresh_token",
					value: refreshToken,
					redirectUri: ConfigService.config.UNITY_URL + "/aad_redirect"
				}
			})).data;
			if (data.accessToken != null && data.refreshToken != null && data.expiresIn != null) {
				localStorage.setItem("outlookAccessToken", data.accessToken);
				localStorage.setItem("outlookRefreshToken", data.refreshToken);
				localStorage.setItem("outlookExpiresAt", addSecondsToCurrentTimeUnix(data.expiresIn));
				return data.accessToken;
			} else throw new Error("Error: unable to get access token");
		} catch (error_0) {
			console.error("Error refreshing access token:", error_0);
			return null;
		}
	};
	const login = () => {
		const baseUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize";
		let clientId;
		if (process !== void 0) clientId = process.env.REACT_APP_MSAL_API_CLIENT_ID;
		else clientId = ConfigService.config.MSAL_API_ACCESS_SCOPE?.split("/")[0];
		const responseType = "code";
		const redirectUri = `${ConfigService.config.UNITY_URL}/aad_redirect`;
		const responseMode = "query";
		const scope = [
			"https://graph.microsoft.com/Calendars.ReadWrite",
			"https://graph.microsoft.com/Calendars.ReadWrite.Shared",
			"https://graph.microsoft.com/OnlineMeetingTranscript.Read.All",
			"https://graph.microsoft.com/OnlineMeetings.Read"
		].join("%20");
		openLoginPopup(`${baseUrl}?client_id=${clientId}&response_type=${responseType}&redirect_uri=${redirectUri}&response_mode=${responseMode}&scope=${scope}&state=${callbackUri}`);
	};
	function openLoginPopup(url) {
		var width = 600;
		var height = 600;
		var left = (screen.width - width) / 2;
		var features = `width=${width},height=${height},top=${(screen.height - height) / 2},left=${left},status=no,toolbar=no,menubar=no,location=no`;
		return window.open(url, "LoginPopup", features);
	}
	function addSecondsToCurrentTimeUnix(seconds) {
		var now = /* @__PURE__ */ new Date();
		now.setSeconds(now.getSeconds() + seconds);
		return now.getTime();
	}
	function isBeforeCurrentTime(unixTime) {
		return unixTime < (/* @__PURE__ */ new Date()).getTime();
	}
	const isUserSignedIn = () => {
		const accessToken_0 = localStorage.getItem("outlookAccessToken");
		const refreshToken_0 = localStorage.getItem("outlookRefreshToken");
		const expiresAt_0 = localStorage.getItem("outlookExpiresAt");
		if (accessToken_0 && refreshToken_0 && expiresAt_0 && !isBeforeCurrentTime(expiresAt_0)) return true;
		else return false;
	};
	useEffect(() => {
		const handleStorageChange = (event) => {
			if (event.key === "outlookAccessToken") onLogin();
		};
		window.addEventListener("storage", handleStorageChange);
		return () => {
			window.removeEventListener("storage", handleStorageChange);
		};
	}, []);
	return {
		getAccessToken,
		invalidateUserSession,
		login,
		isUserSignedIn
	};
};
//#endregion
export { useOutlook };

//# sourceMappingURL=useOutlook.mjs.map