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

const gatewayUrl = env.GATEWAY_URL || 'http://localhost:8100';
const devAutoLogin = ['1', 'true', 'yes', 'on'].includes((env.DEV_AUTO_LOGIN || '').toLowerCase());

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

	try {
		const headers: Record<string, string> = {};
		if (session) headers.Cookie = `platform_session=${session}`;
		if (devAutoLogin && onTestHost) headers['X-Dev-Auto-Login'] = '1';
		const res = await fetch(`${gatewayUrl}/api/auth/me`, {
			headers
		});
		if (res.ok) {
			const data = await res.json();
			if (data.authenticated) {
				const allApps = ['tasks', 'trips', 'fitness', 'inventory', 'budget', 'reader', 'media'];
				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 };
			}
		}
	} catch { /* gateway down */ }

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