<script lang="ts">
	import { goto } from "$app/navigation";
	import apiFetch, { TOKEN_KEY, type AuthCallback } from "$lib/api";
	import { addToast } from "$lib/toast";
	import { onMount } from "svelte";
	import type { PageData } from "./$types";

	let error = false;

	export let data: PageData;

	onMount(async () => {
		const params = new URLSearchParams(window.location.search);
		const code = params.get("code");
		const state = params.get("state");
		const guildId = params.get("guild_id");

		if (data.user) {
			if (guildId) return await goto(`/dash/${guildId}`);

			addToast({ header: "Cannot log in", body: "You are already logged in." });
			await goto("/dash");
			return;
		}

		if (!code || !state) {
			addToast({
				header: "Cannot log in",
				body: "Missing 'code' or 'state' parameters.",
			});
			await goto("/");
			return;
		}

		try {
			const resp = await apiFetch<AuthCallback>("POST", "/api/callback", {
				code,
				state,
			});

			localStorage.setItem(TOKEN_KEY, resp.token);

			if (guildId) {
				await goto(`/dash/${guildId}`, { invalidateAll: true });
			} else {
				await goto("/dash", { invalidateAll: true });
			}
		} catch (e) {
			console.error("Callback request failed: ", e);
			error = true;
		}
	});
</script>

{#if !error}
	<h1>Loading...</h1>
	<p>You should be redirected to the dashboard within a few seconds.</p>
{:else}
	<h1>Could not log in</h1>
	<p>An error occurred while logging in with Discord. Please try again.</p>
{/if}
