<script lang="ts">
    import {onMount} from "svelte";
    import {enforce_auth, enforce_session} from "$lib/auth";
    import {Logger, logSetup} from "$lib/logger";
    import {list_org} from "$lib/orgs";
    import {t} from "$lib/i18n";
    import FullPageError from "../../../../components/FullPageError.svelte";
    import {get_user_info} from "$lib/auth";
    import {org} from "$lib/orgs";
    import type {Organization} from "$lib/orgs";
    import {API_ROOT} from "$lib/config";
    import {fetch_timeout} from "$lib/util";
    import {page} from "$app/stores";
    import OrgWrapper from "$components/org/OrgWrapper.svelte";

    let logger = new Logger("org/[orgid]/relays/+page.svelte");
    logSetup();

    let orgid = $page.params.orgid;

    let api_token = "";

    let fullPageError = false;
    let fullPageErrorTitle = "";
    let fullPageErrorSubtitle = "";

    let user_info;

    // this page requires session and mfa auth.
    onMount(async () => {
        let st_result = await enforce_session();
        if (!st_result[0]) {
            // Session token is invalid. redirect to login
            window.location = "/auth/login";
            return;
        }
        let at_result = await enforce_auth();
        if (!at_result[0]) {
            // Auth token is invalid. Redirect to mfa page.
            window.location = "/auth/mfa";
            return;
        }
        // user is fully authenticated and permitted to proceed
        api_token = at_result[1];
        logger.info("User authenticated successfully");

        // GET USER INFO
        user_info = await get_user_info(api_token);
        if (typeof user_info === "string") {
            logger.error(user_info);
            fullPageError = true;
            fullPageErrorTitle = t('admin.apierror.loaduser');
            fullPageErrorSubtitle = t('admin.apierror.' + user_info);
            return;
        }

        let org_list: string | number[] = await list_org(api_token);
        if (typeof org_list === "string") {
            // Error
            logger.error(org_list);
            fullPageError = true;
            fullPageErrorTitle = t('org.apierror.loadorg');
            fullPageErrorSubtitle = t('org.apierror.' + org_list);
            return;
        }
        let list: number[] = org_list;

        if (!list.includes(Number(orgid))) {
            fullPageError = true;
            fullPageErrorTitle = t('org.apierror.notyourorg');
            fullPageErrorSubtitle = t('org.apierror.notyourorgexplainer');
            return;
        }
    })
</script>

{#if fullPageError}
    <FullPageError title="{fullPageErrorTitle}" subtitle="{fullPageErrorSubtitle}"/>
{:else}
    <!-- BREAKING THE LAYOUT! -->

    <!-- Sidenav :O -->
    <OrgWrapper selected="relays" orgid="{orgid}">

    </OrgWrapper>
{/if}