import { WebStorageStateStore } from "oidc-client-ts";

let accessToken: string | null = null;

function getStoredAccessToken(): string | null {
	if (typeof window === "undefined" || !isOidcConfigured()) {
		return null;
	}

	const authority = import.meta.env.VITE_OIDC_ISSUER as string;
	const clientId = import.meta.env.VITE_OIDC_CLIENT_ID as string;
	const raw = window.localStorage.getItem(`oidc.user:${authority}:${clientId}`);
	if (!raw) {
		return null;
	}

	try {
		const parsed = JSON.parse(raw) as { access_token?: unknown };
		return typeof parsed.access_token === "string" && parsed.access_token
			? parsed.access_token
			: null;
	} catch {
		return null;
	}
}

export function isOidcConfigured(): boolean {
	const enabled =
		(import.meta.env.VITE_OIDC_ENABLED ?? "true").toLowerCase() !== "false";
	return Boolean(
		enabled &&
			import.meta.env.VITE_OIDC_ISSUER &&
			import.meta.env.VITE_OIDC_CLIENT_ID,
	);
}

export function getOidcConfig() {
	const storage = new WebStorageStateStore({
		store: window.localStorage,
	});

	return {
		authority: import.meta.env.VITE_OIDC_ISSUER as string,
		client_id: import.meta.env.VITE_OIDC_CLIENT_ID as string,
		redirect_uri:
			import.meta.env.VITE_OIDC_REDIRECT_URI || window.location.origin,
		post_logout_redirect_uri:
			import.meta.env.VITE_OIDC_POST_LOGOUT_REDIRECT_URI ||
			window.location.origin,
		scope: import.meta.env.VITE_OIDC_SCOPE || "openid profile email",
		response_type: "code" as const,
		automaticSilentRenew: true,
		loadUserInfo: true,
		stateStore: storage,
		userStore: storage,
		onSigninCallback: () => {
			// Remove the OIDC response params so a reload doesn't try to process
			// the same callback twice and fail with a missing state entry.
			window.history.replaceState({}, document.title, window.location.pathname);
		},
	};
}

export function setAccessToken(token: string | null | undefined) {
	accessToken = token ?? null;
}

export function getAccessToken(): string | null {
	return accessToken ?? getStoredAccessToken();
}
