import { redirect } from '@sveltejs/kit';
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals, url }) => {
	const { session, user, member } = await locals.safeGetSession();

	// Require authentication for all app routes
	if (!session) {
		throw redirect(303, `/login?redirectTo=${encodeURIComponent(url.pathname)}`);
	}

	// Require member profile to exist
	if (!member) {
		// User is authenticated but has no member profile - unusual situation
		await locals.supabase.auth.signOut();
		throw redirect(303, '/login?error=no_profile');
	}

	// Check if user's email is verified
	const emailVerified = user?.email_confirmed_at !== null && user?.email_confirmed_at !== undefined;

	return {
		session,
		member,
		emailVerified
	};
};
