import { env } from '$env/dynamic/private';
import { redirect, type Handle } from '@sveltejs/kit';
import { jwtVerify } from 'jose';

export const handle: Handle = async ({ event, resolve }) => {
    if (event.url.pathname !== "/login") {
        const token = event.cookies.get("auth");
        const secret = new TextEncoder().encode(env.AUTH_SECRET);
        const authenticated = token != null && await jwtVerify(token, secret)
            .then(() => true)
            .catch(() => false);
        if (!authenticated) redirect(307, "/login");
    }

    return await resolve(event);
};
