import Keycloak from "keycloak-js";

const authMode = (import.meta.env.VITE_AUTH_MODE || "legacy").toLowerCase();

export const isOidcEnabled = authMode === "keycloak" || authMode === "hybrid";
export const isOidcRequired = authMode === "keycloak";

const keycloak = isOidcEnabled
	? new Keycloak({
			url: import.meta.env.VITE_KEYCLOAK_URL,
			realm: import.meta.env.VITE_KEYCLOAK_REALM,
			clientId: import.meta.env.VITE_KEYCLOAK_CLIENT_ID,
	  })
	: null;

let initializationPromise = null;
let initialized = false;

function redirectUri() {
	return `${window.location.origin}${window.location.pathname}`;
}

export async function initializeKeycloak({
	loginRequired = isOidcRequired,
	checkSso = false,
} = {}) {
	if (!isOidcEnabled) {
		return false;
	}
	if (!initializationPromise) {
		const options = {
			pkceMethod: "S256",
			locale: "zh-CN",
			redirectUri: redirectUri(),
			responseMode: "query",
			checkLoginIframe: false,
		};
		if (loginRequired) {
			options.onLoad = "login-required";
		} else if (checkSso) {
			options.onLoad = "check-sso";
		}
		initializationPromise = keycloak
			.init(options)
			.then((authenticated) => {
				initialized = true;
				return authenticated;
			})
			.catch((error) => {
				initializationPromise = null;
				throw error;
			});
	}
	const authenticated = await initializationPromise;
	keycloak.onTokenExpired = () => {
		keycloak.updateToken(30).catch(() => keycloak.login());
	};
	return authenticated;
}

export async function loginWithIdentityProvider() {
	if (!isOidcEnabled || !keycloak) {
		throw new Error("统一认证登录未启用");
	}
	await initializeKeycloak({ loginRequired: false });
	await keycloak.login({
		redirectUri: redirectUri(),
		locale: "zh-CN",
	});
}

export function getKeycloakAccessToken() {
	return keycloak && keycloak.token;
}

export async function logoutFromIdentityProvider() {
	if (
		!isOidcEnabled ||
		!keycloak ||
		!initialized ||
		!keycloak.authenticated
	) {
		return false;
	}
	await keycloak.logout({ redirectUri: window.location.origin });
	return true;
}

export default keycloak;
