<script lang="ts">
    import Button from "$lib/ui/button.svelte";
    import {
        clearTokens,
        createSb1SyncSessionAndReturnLoginUrl,
        getAccounts,
        getTokenExpires,
        getTransactions,
        refreshSB1Token,
    } from "./sb1.remote";

    let navigating = $state(false);

    async function authorize() {
        navigating = true;
        const url = await createSb1SyncSessionAndReturnLoginUrl();
        location.href = url;
        navigating = false;
    }

    async function clearAuth() {
        await clearTokens();
        getTokenExpires().refresh();
    }

    async function refreshAuth() {
        await refreshSB1Token();
        getTokenExpires().refresh();
    }
</script>

<main>
    {#if await getTokenExpires()}
        {@const tokens = await getTokenExpires()}
        {@const accounts = await getAccounts()}
        {#if tokens}
            <pre>accessToken: {tokens.accessToken.created.add({ seconds: tokens.accessToken.expires }).toLocaleString()}
refreshToken: {tokens.refreshToken.created.add({ seconds: tokens.refreshToken.expires }).toLocaleString()}</pre>
            <ul>
                {#each accounts.accounts as account}
                    {@const transactions = await getTransactions(account.key)}
                    <li>{account.name}</li>
                    <ul>
                        {#each transactions?.transactions as transaction}
                            <li>{JSON.stringify(transaction)}</li>
                        {/each}
                    </ul>
                {/each}
            </ul>
        {:else}
            <Button onclick={clearAuth}>Slett autorisasjon</Button>
            <Button onclick={refreshAuth}>Oppdater autorisasjon</Button>
        {/if}
    {:else}
        <Button onclick={authorize} loading={navigating}>Autentisér hos Sparebanken 1</Button>
    {/if}
</main>

<style>
    pre {
        max-width: 50vw;
        overflow: auto;
    }
</style>
