<script>
    import { onMount }       from 'svelte';
    import { useTinyRouter } from 'svelte-tiny-router';

    import { api }           from '../../urls.svelte.js';
    import { t }             from '../../translations.svelte.js';
    import { checkUser }     from '../../user.svelte.js';

    const router = useTinyRouter();
    let message  = $state(t('processing_code'));

    async function process(){
        let params = new URLSearchParams(location.search);

        if (params.get('code')){
            const url = api('user/oidc/token');
            const resp = await fetch(url,{
                method      : 'POST',
                body        : JSON.stringify(Object.fromEntries(params)),
                credentials : 'include'
            });
            if (resp.ok){
                let json       = await resp.json();
                const redirect = json.redirect ? json.redirect : '/user';
                checkUser();
                router.navigate(redirect);
            } else {
                message = await resp.text();
                if (!message) message = t(resp);
            }
        }
    }

    onMount(process);
</script>

{message}