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

export const load: PageServerLoad = async ({ cookies }) => {
	const sessionToken = cookies.get('ory_kratos_session');

	if (!sessionToken) {
		redirect(303, '/login?return_to=/admin');
	}

	try {
		const { data: session } = await kratosServerClient.toSession({
			cookie: `ory_kratos_session=${sessionToken}`
		});

		// Check if the user is the admin
		if (session.identity?.id !== ADMIN_USER_ID) {
			redirect(303, '/?error=unauthorized');
		}

		return {
			session,
			isAdmin: true
		};
	} catch {
		// If session validation fails, redirect to login
		redirect(303, '/login?return_to=/admin');
	}
};
