import { redirect, fail, isRedirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import type { Actions, PageServerLoad } from './$types';
import { clearAuthTokens, getAuthTokens } from '$lib/server/api';
import { setAccessTokenCookies } from '$lib/server/access-token-cookie';
import {
	readWorkspaceReturnPath,
	clearWorkspaceReturnPath,
	redirectToWorkspaceLogin,
	getHubBackendUrl,
	isSecureContext,
} from '$lib/server/workspace-auth';

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

export const load: PageServerLoad = async ({ cookies, url }) => {
	// Modo local: mostrar el form de login sin redirigir al workspace
	if (DEV_LOCAL_AUTH) {
		// Solo limpiar si ya hay token (re-login explícito), no en cada carga
		const { accessToken } = getAuthTokens(cookies);
		if (accessToken) clearAuthTokens(cookies);
		return { devMode: true };
	}

	// Relay SSO: el Hub App Launcher redirige aquí con ?relay=UUID4.
	const relayToken = url.searchParams.get('relay');
	if (relayToken) {
		try {
			const hubBackendUrl = getHubBackendUrl();
			const exchangeRes = await fetch(`${hubBackendUrl}/api/v1/auth/sso-exchange`, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({ relay_token: relayToken })
			});

			if (exchangeRes.ok) {
				const data = await exchangeRes.json();
				const isProduction = isSecureContext();
				setAccessTokenCookies(cookies, data.access_token, {
					secure: isProduction,
					maxAge: 60 * 60 * 24 * 7
				});
				if (data.refresh_token) {
					cookies.set('refresh_token', data.refresh_token, {
						path: '/',
						httpOnly: true,
						secure: isProduction,
						sameSite: 'lax',
						maxAge: 60 * 60 * 24 * 30
					});
				}
				const redirectTo =
					url.searchParams.get('redirect') ||
					readWorkspaceReturnPath(cookies, '/dashboard');
				clearWorkspaceReturnPath(cookies);
				throw redirect(303, redirectTo);
			}
		} catch (err) {
			if (isRedirect(err)) throw err;
		}
	}

	clearAuthTokens(cookies);

	// Vuelta desde el Workspace tras autenticarse: el CRM NO inicia ningún flujo
	// OIDC contra Keycloak. La sesión se obtiene por relay del App Launcher
	// (→ /auth/sso). Si el usuario llega aquí ya autenticado en el Hub, se le
	// manda al dashboard; si no hay sesión local, el layout lo reenvía al
	// Workspace (App Launcher) para re-entrar por relay.
	if (url.searchParams.get('sso_verified') === '1') {
		throw redirect(303, '/dashboard');
	}

	// Sin sesión → App Launcher del Workspace (relay). Nunca Keycloak directo.
	redirectToWorkspaceLogin(cookies, url);
};

export const actions: Actions = {
	dev_login: async ({ cookies, request }) => {
		if (!DEV_LOCAL_AUTH) throw redirect(303, '/login');

		const BACKEND_URL = env.BACKEND_URL || 'http://backend:8000';

		const res = await fetch(`${BACKEND_URL}/api/v1/auth/dev-login`, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' }
		});

		if (!res.ok) {
			return fail(500, { error: 'No se pudo generar el token local. Verifica que DEV_LOCAL_AUTH=true en el backend.' });
		}

		const { access_token } = await res.json();

		setAccessTokenCookies(cookies, access_token, {
			secure: false,
			maxAge: 60 * 60 * 8
		});

		throw redirect(303, '/dashboard');
	}
};
