<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]/roles/+page.svelte");
    logSetup();

    let orgid = $page.params.orgid;

    let api_token = "";

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

    let user_info;

    let roles = {
        'data': []
    };

    // 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;
        }


    })

    let name = "";
    let description = "";

    async function createRole() {
        try {
            let resp = await fetch_timeout(`${API_ROOT}/v1/org/${orgid}/role`, {
                'method': 'POST',
                'headers': {
                    'Authorization': `Bearer ${api_token}`
                },
                'body': JSON.stringify({
                    'name': name,
                    'description': description
                })
            });
            if (!resp.ok) {
                let err = JSON.parse(await resp.text()).errors[0].message;
                logger.error(`${err}`);
                fullPageError = true;
                fullPageErrorTitle = t('org.apierror.addrole');
                fullPageErrorSubtitle = t('org.apierror.' + err);
                return;
            }
            roles = JSON.parse(await resp.text());
            window.location.href = `/org/${orgid}/roles`
        } catch (e) {
            logger.error(`${e}`);
            fullPageError = true;
            fullPageErrorTitle = t('org.apierror.loadroles');
            fullPageErrorSubtitle = t('org.apierror.' + `${e}`.replaceAll('.', ''));
            return;
        }
    }
</script>

{#if fullPageError}
    <FullPageError title="{fullPageErrorTitle}" subtitle="{fullPageErrorSubtitle}"/>
{:else}
    <div class="flex in-h-full items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
        <div class="w-full max-w-md">

                <!-- The actual form -->
                <form class="mt-5" action="#" method="POST" on:submit|preventDefault={createRole}>
                    <div class="rounded-md shadow-sm">
                        <label for="name">{t('org.roleaddprompt')}</label>
                        <input bind:value={name} id="name"
                               class="dark:bg-slate-500 bg-gray-200 w-full rounded px-3 py-2 focus:outline-none focus:ring-purple-500 appearance-none">
                    </div>

                    <div class="rounded-md shadow-sm mt-5">
                        <label for="desc">{t('org.roleaddpromptdesc')}</label>
                        <input bind:value={description} id="desc"
                               class="dark:bg-slate-500 bg-gray-200 w-full rounded px-3 py-2 focus:outline-none focus:ring-purple-500 appearance-none">
                    </div>

                    <button class="bg-purple-400 dark:bg-purple-600 mt-4 w-full py-2 -space-y-px rounded-md shadow-sm place-content-center">
                            {t('org.roleadd_cta')}
                    </button>

                </form>
        </div>
    </div>
{/if}