import type { Handle } from '@sveltejs/kit';
import { paraglideMiddleware } from '$lib/paraglide/server';
import { sequence } from '@sveltejs/kit/hooks';
import { getAccessTokenFromCookies } from '$lib/server/access-token-cookie';

const handleParaglide: Handle = ({ event, resolve }) => paraglideMiddleware(event.request, ({ request, locale }) => {
	event.request = request;

	return resolve(event, {
		transformPageChunk: ({ html }) => html.replace('%paraglide.lang%', locale)
	});
});

const handleAuth: Handle = async ({ event, resolve }) => {
	// Obtener el token de las cookies
	const token = getAccessTokenFromCookies(event.cookies);
	
	// Agregar el token a los locals para que esté disponible en toda la app
	event.locals.token = token || null;
	event.locals.isAuthenticated = !!token;

	return resolve(event);
};

export const handle: Handle = sequence(handleAuth, handleParaglide);
