import { ApiClient } from '$lib/server/api';
import { validateToken } from '$lib/server/auth';
import { redirect, type Handle } from '@sveltejs/kit';
import { sequence } from '@sveltejs/kit/hooks';

const authHandle: Handle = async ({ event, resolve }) => {
	// Get auth token from cookies
	const authToken = event.cookies.get('authToken');

	if (authToken) {
		// Validate the token
		const api = new ApiClient(authToken);
		const user = await validateToken(api);

		if (user) {
			// Token is valid
			event.locals.user = user;
			event.locals.authToken = authToken;
			event.locals.api = api;
		} else {
			// Token invalid, clear auth cookie
			event.cookies.delete('authToken', { path: '/' });
		}
	}

	return resolve(event);
};

const protectedRoutesHandle: Handle = async ({ event, resolve }) => {
	const isProtectedRoute = !event.url.pathname.startsWith('/login');

	if (isProtectedRoute && !event.locals.user) throw redirect(303, '/login');

	return resolve(event);
};

export const handle = sequence(authHandle, protectedRoutesHandle);
