import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getAccessTokenFromCookies } from '$lib/server/access-token-cookie';
import {
	extractAllowedSystemsFromToken,
	fetchAllowedSystems,
	isValidSystem,
	mergeTokenClaims,
	setActiveSystemCookie
} from '$lib/server/system-gate';

export const POST: RequestHandler = async ({ cookies, request }) => {
	try {
		const { system } = await request.json();

		if (!isValidSystem(system)) {
			return json({ error: 'Sistema inválido' }, { status: 400 });
		}

		const accessToken = getAccessTokenFromCookies(cookies);
		if (!accessToken) {
			return json({ error: 'No autenticado' }, { status: 401 });
		}

		const tokenClaims = mergeTokenClaims(null, accessToken);
		let allowedSystems = extractAllowedSystemsFromToken(tokenClaims);

		if (allowedSystems.length === 0) {
			const rawCompanyId = cookies.get('active_company_id');
			const companyId = rawCompanyId ? Number.parseInt(rawCompanyId, 10) : NaN;
			if (Number.isFinite(companyId)) {
				allowedSystems = await fetchAllowedSystems(cookies, fetch, companyId);
			}
		}

		if (!allowedSystems.includes(system)) {
			return json({ error: 'No tienes acceso a ese sistema' }, { status: 403 });
		}

		setActiveSystemCookie(cookies, system);

		return json({ success: true, system });
	} catch {
		return json({ error: 'Internal server error' }, { status: 500 });
	}
};
