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

export const POST: RequestHandler = async ({ cookies, url }) => {
	const systemBaseUrl = url.origin;

	const idToken = cookies.get('id_token');

	// Eliminar todas las cookies de autenticación
	clearAccessTokenCookies(cookies);
	cookies.delete('refresh_token', { path: '/' });
	cookies.delete('id_token', { path: '/' });
	cookies.delete('active_company_id', { path: '/' });
	cookies.delete('active_system', { path: '/' });
	cookies.delete('sso_tenant_id', { path: '/' });
	cookies.delete('sso_tenant_pub', { path: '/' });
	clearWorkspaceReturnPath(cookies);

	// En modo local no hay Keycloak ni Hub — ir directo al login local.
	if ((env.DEV_LOCAL_AUTH ?? '').toLowerCase() === 'true') {
		throw redirect(303, '/login');
	}

	// Sin id_token_hint KC rechaza post_logout_redirect_uri no registrado.
	if (!idToken) {
		throw redirect(303, getWorkspaceLoginUrl(systemBaseUrl, { forPostLogout: true }));
	}

	throw redirect(303, buildKeycloakLogoutUrl(systemBaseUrl, idToken));
};
