import { env } from '$env/dynamic/private';
import type { LayoutServerLoad } from './$types';
import {
	validateAuth,
	getAuthTokens,
	getKcAccessToken,
	getUserCompanies,
	clearAuthTokens
} from '$lib/server/api';
import { redirectToWorkspaceLogin } from '$lib/server/workspace-auth';
import { resolveActiveCompanyId } from '$lib/server/system-gate';
import { fetchMyApps } from '$lib/server/workspace-apps';

const DEV_LOCAL_AUTH = (env.DEV_LOCAL_AUTH ?? '').toLowerCase() === 'true';

export const load: LayoutServerLoad = async ({ cookies, url, fetch }) => {
	const { accessToken } = getAuthTokens(cookies);

	if (!accessToken) {
		redirectToWorkspaceLogin(cookies, url);
	}

	try {
		// my-companies primero: ejecuta get_current_user y provisiona tenant/usuario si aplica.
		const companies = await getUserCompanies(cookies, fetch);
		const userData = await validateAuth(cookies, fetch, undefined);
		const activeCompanyId = resolveActiveCompanyId(cookies, companies);

		// Modo local: no hay Hub. Saltar fetch de tenants/apps (evita timeouts por navegación).
		let userTenants: { id: number; name: string; slug: string }[] = [];
		let myApps: { apps: unknown[]; routing: unknown } = { apps: [], routing: null };

		if (!DEV_LOCAL_AUTH) {
			// Llamadas DIRECTAS al Hub → token KC (con el patrón de sesión local, el
			// access_token guarda la sesión local del CRM, no el token de Keycloak).
			const kcToken = getKcAccessToken(cookies) ?? accessToken;
			try {
				const hubUrl = (env.INTERNAL_HUB_URL || env.HUB_URL || 'http://localhost:8001').replace(/\/+$/, '');
				const tenantOverride = cookies.get('sso_tenant_id');
				const tenantsRes = await fetch(`${hubUrl}/api/v1/auth/my-tenants`, {
					headers: {
						'Authorization': `Bearer ${kcToken}`,
						...(tenantOverride ? { 'X-Tenant-Override': tenantOverride } : {})
					}
				});
				if (tenantsRes.ok) {
					userTenants = await tenantsRes.json();
				}
			} catch {
				// No bloquear el dashboard si falla la carga de tenants
			}

			myApps = await fetchMyApps(kcToken, fetch, cookies.get('sso_tenant_id'));
		}

		return {
			authenticated: true,
			user: { ...userData, token: accessToken },
			companies,
			activeCompanyId: activeCompanyId ?? undefined,
			userTenants,
			workspaceApps: myApps.apps,
			appRouting: myApps.routing,
			error: undefined
		};
	} catch (error) {
		// Si es un redirect, re-lanzarlo sin tocar las cookies
		if (error && typeof error === 'object' && 'status' in error && 'location' in error) {
			throw error;
		}

		// Cualquier otro error: limpiar token y redirigir al login
		clearAuthTokens(cookies);
		redirectToWorkspaceLogin(cookies, url);
	}
};
