<script>
	import { uploadID } from "$lib/services/lnv";
	import { getOIDCUser } from "$lib/services/oidc";
	import { onMount } from "svelte";

	const url = new URL(location.href);
	const code = url.searchParams.get("code");
	const state = url.searchParams.get("state");
	const storedState = localStorage.getItem("lnv-oidcstate");
	const codeVerifier = localStorage.getItem("lnv-codeVerifier");
	localStorage.removeItem("lnv-oidcstate");
	localStorage.removeItem("lnv-codeVerifier");

	async function login() {
		if (!code || !state || !codeVerifier || !storedState) {
			alert("Missing code, state, codeVerifier or storedState.");
			return;
		}
		if (state !== storedState) {
			alert("State mismatch. Please try again.");
			return;
		}

		const token = await getOIDCUser(code, codeVerifier);
		localStorage.setItem("lnv-id", token.id_token);
		localStorage.setItem("lnv-token", token.access_token);
		localStorage.setItem("lnv-refresh", token.refresh_token);
		await uploadID();
	}

	onMount(async () => {
		await login();
		location.href = "/";
	});
</script>
