<script lang="ts">
    import {isLoading, t} from "svelte-i18n";
    import LoadingWrapper from "$components/LoadingWrapper.svelte";
    import {onMount} from "svelte";
    import {APIResult, verifyLink} from "$lib/auth.ts";
    import type {APIError} from "$lib/auth.ts";
    import {Logger, logSetup} from "$lib/logger";

    let loading = true;
    let isError = false;
    let error = '';
    $: currentlyLoading = $isLoading || loading;

    logSetup();
    let logger = new Logger("magic-link/+page.svelte");

    onMount(async () => {
        let url = new URLSearchParams(window.location.search);
        if (!url.has("magicLinkToken")) {
            logger.error('url does not contain magicLinkToken');
            isError = true;
            error = $t("ml.error.notoken");
        }

        let call_result = await verifyLink(url.get("magicLinkToken"));

        if (call_result[0] !== APIResult.Successful) {
            let err = (call_result[1] as APIError).code;

            if (err === "ERR_UNAUTHORIZED" || err === "ERR_EXPIRED") {
                error = $t('ml.error.badtoken');
            } else {
                error = err;
            }

            isError = true;
            loading = false;
            setTimeout(() => window.location.href = "/login", 1000);
        } else {
            loading = false;
            window.location.href = "/admin";
        }

    })
</script>

<svelte:head>
    <title>{$t("common.title", {values: {title: $t("common.page.login")}})}</title>
</svelte:head>

<LoadingWrapper isLoading={currentlyLoading} isError={isError} error={error}>
    <h1>{$t('ml.header')}</h1>
    <p>{$t('ml.body')}</p>
</LoadingWrapper>
