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

const gatewayUrl = env.GATEWAY_URL || 'http://localhost:8100';

export const load: LayoutServerLoad = async ({ cookies, url }) => {
	const host = url.host.toLowerCase();
	const useAtelierShell = host.includes(':4174') || host.startsWith('test.');
	const session = cookies.get('platform_session');
	if (!session) {
		throw redirect(302, `/login?redirect=${encodeURIComponent(url.pathname)}`);
	}

	// Validate session is still active
	try {
		const res = await fetch(`${gatewayUrl}/api/auth/me`, {
			headers: { Cookie: `platform_session=${session}` }
		});
		if (res.ok) {
			const data = await res.json();
			if (data.authenticated) {
				// Per-user nav visibility — COSMETIC ONLY.
				// Hides nav items but does NOT block direct URL access.
				// This is intentional: all shared services are accessible to all authenticated users.
				// Hiding reduces clutter for users who don't need certain apps day-to-day.
				const allApps = ['tasks', 'trips', 'fitness', 'inventory', 'budget', 'reader', 'media', 'brain'];
				const hiddenByUser: Record<string, string[]> = {
					'madiha': ['inventory', 'reader'],
				};
				const hidden = hiddenByUser[data.user.username] || [];
				const visibleApps = allApps.filter(a => !hidden.includes(a));
				return { user: data.user, visibleApps, useAtelierShell };
			}
		}
	} catch { /* gateway down — let client handle */ }

	// Invalid/expired session
	throw redirect(302, `/login?redirect=${encodeURIComponent(url.pathname)}`);
};
