/**
 * Endpoint server-side para cambiar de tenant sin exponer el refresh_token al cliente.
 *
 * Dos modos:
 * - { tenant_id } → flujo SSO relay: solo actualiza cookie sso_tenant_id (override de tenant)
 * - { tenant_slug } → flujo login clásico: re-emite tokens KC para el nuevo tenant
 */

import { json } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import type { RequestEvent } from '@sveltejs/kit';
import { getServerApiUrl, getAuthTokens, setAuthTokens } from '$lib/server/api';

export const POST = async ({ request, cookies, fetch }: RequestEvent) => {
	const body = await request.json();
	const { tenant_id, tenant_slug } = body as { tenant_id?: number; tenant_slug?: string };

	if (!tenant_id && !tenant_slug) {
		return json({ error: 'tenant_id or tenant_slug is required' }, { status: 400 });
	}

	const { accessToken, refreshToken } = getAuthTokens(cookies);

	if (!accessToken) {
		return json({ error: 'Not authenticated' }, { status: 401 });
	}

	// Modo SSO relay: validar acceso vía Hub y actualizar cookie de override
	if (tenant_id) {
		try {
			const hubUrl = (env.INTERNAL_HUB_URL || env.HUB_URL || 'http://localhost:8001').replace(/\/+$/, '');
			const tenantsRes = await fetch(`${hubUrl}/api/v1/auth/my-tenants`, {
				headers: { 'Authorization': `Bearer ${accessToken}` },
			});
			if (!tenantsRes.ok) {
				return json({ error: 'Could not validate tenant access' }, { status: 403 });
			}
			const tenants: { id: number }[] = await tenantsRes.json();
			const hasAccess = tenants.some((t) => t.id === tenant_id);
			if (!hasAccess) {
				return json({ error: 'Access denied to tenant' }, { status: 403 });
			}
			const isProduction = process.env.NODE_ENV === 'production';
			cookies.set('sso_tenant_id', String(tenant_id), {
				path: '/',
				httpOnly: true,
				secure: isProduction,
				sameSite: 'lax',
				maxAge: 60 * 60 * 24 * 7,
			});
			cookies.set('sso_tenant_pub', String(tenant_id), {
				path: '/',
				httpOnly: false,
				secure: isProduction,
				sameSite: 'lax',
				maxAge: 60 * 60 * 24 * 7,
			});
			cookies.delete('active_company_id', { path: '/' });
			return json({ ok: true });
		} catch (error) {
			console.error('[switch-tenant] SSO mode error:', error);
			return json({ error: 'Internal server error' }, { status: 500 });
		}
	}

	// Modo login clásico: re-emitir tokens KC para el nuevo tenant
	if (!refreshToken) {
		return json({ error: 'Not authenticated' }, { status: 401 });
	}

	try {
		const baseUrl = getServerApiUrl();
		const response = await fetch(`${baseUrl}v1/auth/switch-tenant`, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'Authorization': `Bearer ${accessToken}`,
			},
			body: JSON.stringify({ tenant_slug, refresh_token: refreshToken }),
		});

		if (!response.ok) {
			const err = await response.json().catch(() => ({}));
			return json({ error: err.detail || 'Switch failed' }, { status: response.status });
		}

		const data = await response.json();
		setAuthTokens(cookies, data.access_token, data.refresh_token);
		cookies.delete('active_company_id', { path: '/' });
		cookies.delete('sso_tenant_id', { path: '/' });
		cookies.delete('sso_tenant_pub', { path: '/' });
		return json({ ok: true });
	} catch (error) {
		console.error('[switch-tenant] Classic mode error:', error);
		return json({ error: 'Internal server error' }, { status: 500 });
	}
};
