import { redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';
import type { RequestHandler } from './$types';
import { clearAccessTokenCookies } from '$lib/server/access-token-cookie';

export const POST: RequestHandler = async ({ cookies, request }) => {
	const refreshToken = cookies.get('refresh_token');

	// Redirigir al workspace (Hub) — es el sistema central de autenticación.
	const hubPublicUrl = (env.HUB_URL || '').replace(/\/+$/, '');
	const postLogoutUrl = hubPublicUrl
		? `${hubPublicUrl}/login`
		: `${new URL(request.url).origin}/login`;

	// Eliminar todas las cookies de autenticación (access_token puede estar fragmentado)
	clearAccessTokenCookies(cookies);
	cookies.delete('refresh_token', { path: '/' });
	cookies.delete('active_company_id', { path: '/' });
	cookies.delete('sso_tenant_id', { path: '/' });
	cookies.delete('sso_tenant_pub', { path: '/' });

	// Llamar al Hub para revocar el refresh token (best-effort).
	if (refreshToken) {
		try {
			const hubUrl = (env.INTERNAL_HUB_URL || env.HUB_URL || 'http://localhost:8001').replace(/\/+$/, '');
			await fetch(`${hubUrl}/api/v1/auth/logout`, {
				method: 'POST',
				headers: { 'Content-Type': 'application/json' },
				body: JSON.stringify({
					refresh_token: refreshToken,
					post_logout_redirect_uri: postLogoutUrl,
				}),
			});
		} catch {
			// Si falla la llamada al Hub, continuar de todos modos
		}
	}

	throw redirect(303, postLogoutUrl);
};
