<script>
    import { onMount, onDestroy } from 'svelte';
    import { goto } from '$app/navigation';
    import { browser } from '$app/environment';
    import { writable } from 'svelte/store';

    const authorized = writable(true);

    //TODO: When will has a token validation we need to validate the token here
    //tenho que verificar se realmente vai ser feito essa validacao a cada minuto
    const apiUrl = import.meta.env.VITE_API_URL;
    let intervalId = null;

    async function validate() {
        if (!browser) return;
        const m1 = document.cookie.match(/(?:^|; )auth_token=([^;]+)/);
        const token = m1 ? decodeURIComponent(m1[1]) : null;
        if (!token) {
            authorized.set(false);
            goto('/');
            return;
        }
        try {
            const res = await fetch(`${apiUrl}/verify/jwt`, {
                method: 'POST',
                headers: {
                    'content-type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ token })
            });
            const raw = await res.text();
            let body = null;
            if (raw) {
                try {
                    body = JSON.parse(raw);
                } catch (err) {
                    console.error('verify/jwt JSON parse error:', err);
                }
            }
            const isActive = body?.status === 'ok' && body?.data?.status === 'active';
            if (!res.ok || !isActive) throw new Error('inactive-token');
            authorized.set(true);
        } catch (e) {
            authorized.set(false);
            goto('/');
        }
    }

    onMount(() => {
        validate();
        intervalId = setInterval(validate, 600000);
    });

    onDestroy(() => {
        if (intervalId) clearInterval(intervalId);
    });
</script>

{#if $authorized}
    <slot />
{/if}
