import type { Handle } from '@sveltejs/kit';
import * as auth from '$lib/server/auth';

import { initializeEmbeddings } from '$lib/server/bible-embeddings';
import { getAllNKJVVerses } from '$lib/server/xml-bible';

const handleAuth: Handle = async ({ event, resolve }) => {
	const sessionToken = event.cookies.get(auth.sessionCookieName);

	if (!sessionToken) {
		event.locals.user = null;
		event.locals.session = null;

		return resolve(event);
	}

	const { session, user } = await auth.validateSessionToken(sessionToken);

	if (session) {
		auth.setSessionTokenCookie({ cookies: event.cookies }, sessionToken, session.expiresAt);
	} else {
		auth.deleteSessionTokenCookie({ cookies: event.cookies });
	}

	event.locals.user = user;
	event.locals.session = session;

	return resolve(event);
};

export const handle: Handle = handleAuth;

// Initialize embeddings on server start (runs once on module load)
const verses = getAllNKJVVerses();
// await initializeEmbeddings(verses);
