<script>
    import { env } from '$env/dynamic/public';
    import { onMount } from 'svelte';
    import { page } from '$app/stores';
    import { goto } from '$app/navigation';
    import { member, intros } from '../../store.ts';
    import { authenticate } from '../../api.js';

    const code = $page.url.searchParams.get('code');

    let loginFailed = false;

    onMount(async () => {
        const response = await authenticate(code);
        const body = await response.json();

        if (!response.ok)  {
            loginFailed = true
        } else {
            window.localStorage.setItem('token', body.token);

            await member.pullData(body.token);
            await intros.fetchIntros($member.guilds);


            goto(`${env.PUBLIC_APP_BASE_URL}`)
        }
    });
</script>

{#if loginFailed}
    <p style='color: red'>Login failed</p>
{/if}
