import { kratosServerClient } from '$lib/kratos-server';
import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

// Only validate session on the server. Do NOT create/fetch the settings flow here
// so that Kratos' Set-Cookie (csrf) reaches the browser directly when the flow
// is initialized client-side.
export const load: PageServerLoad = async ({ cookies }) => {
	const sessionToken = cookies.get('ory_kratos_session');
	if (!sessionToken) {
		throw redirect(303, '/login');
	}

	const sessionCookie = `ory_kratos_session=${sessionToken}`;
	try {
		await kratosServerClient.toSession({ cookie: sessionCookie });
	} catch {
		throw redirect(303, '/login');
	}
	return {};
};
