import type { PageServerLoad } from './$types';
import { error, redirect } from '@sveltejs/kit';
import { getAuthTokens, getActiveCompanyId, authenticatedFetch } from '$lib/server/api';

export const load: PageServerLoad = async ({ params, cookies, fetch, url }) => {
	const { accessToken } = getAuthTokens(cookies);

	if (!accessToken) {
		throw redirect(302, '/login');
	}

	// Obtener el company_id de la cookie
	const companyId = await getActiveCompanyId(cookies, fetch);

	if (!companyId) {
		throw error(400, 'No se encontró una compañía seleccionada');
	}

	// Leer filtros de query parameters para preseleccionar en creación
	const operationTypeParam = url.searchParams.get('operation_type');
	const invoiceTypeParam = url.searchParams.get('invoice_type');

	// Validar que operation_type sea 'exp' o 'imp'
	let parsedOperationType: string | null = null;
	if (operationTypeParam && (operationTypeParam === 'exp' || operationTypeParam === 'imp')) {
		parsedOperationType = operationTypeParam;
	}

	// Para creación ('new'): siempre operation_type; invoice_type obligatorio solo en importación.
	if (params.id === 'new' && !parsedOperationType) {
		throw redirect(302, '/dashboard');
	}
	if (params.id === 'new' && parsedOperationType === 'imp' && !invoiceTypeParam) {
		throw redirect(302, '/dashboard');
	}

	try {
		let invoiceData: any = null;
		let catalogsData: any = {};
		let defaultSettings: any = null;
		let isCreate = false;
		let legendsData: any = { items: [] };

		// Fetch Default Settings separately if applicable (for creation)
		const settingsPromise = (params.id === 'new' && parsedOperationType && invoiceTypeParam && companyId)
			? authenticatedFetch(
				`v1/a76/invoice-settings/${invoiceTypeParam}?operation_type=${parsedOperationType}&company_id=${companyId}`,
				{},
				cookies,
				fetch
			).then(res => res.ok ? res.json() : null).catch(err => {
				console.error('Error fetching defaults:', err);
				return null;
			})
			: Promise.resolve(null);


		if (params.id === 'new') {
			isCreate = true;
			const creationQs = new URLSearchParams({
				company_id: String(companyId),
				operation_type: parsedOperationType || ''
			});
			if (invoiceTypeParam) {
				creationQs.set('invoice_type', invoiceTypeParam);
			}
			// Call Consolidated Creation Endpoint (RBAC: tipo de alta en query)
			const [creationResponse, settingsResult] = await Promise.all([
				authenticatedFetch(`v1/a76/invoices/creation-data?${creationQs.toString()}`, {}, cookies, fetch),
				settingsPromise
			]);

			if (creationResponse.ok) {
				catalogsData = await creationResponse.json();
			} else if (creationResponse.status === 403) {
				throw error(403, 'No tienes permiso para crear este tipo de factura.');
			} else if (creationResponse.status === 401) {
				throw error(401, 'Tu sesión expiró. Vuelve a iniciar sesión.');
			} else if (creationResponse.status === 422) {
				throw error(422, 'Parámetros inválidos para crear factura.');
			} else {
				console.error('Error fetching creation data:', creationResponse.status);
				throw error(creationResponse.status, 'No fue posible preparar el formulario de creación.');
			}

			if (settingsResult && settingsResult.settings) {
				defaultSettings = settingsResult.settings;
			}

		} else {
			// Edition Mode
			const invoiceId = parseInt(params.id);
			if (isNaN(invoiceId)) {
				throw error(400, 'ID de factura inválido');
			}

			// Call Consolidated Edition Endpoint
			const editionResponse = await authenticatedFetch(
				`v1/a76/invoices/${invoiceId}/edition-data?company_id=${companyId}`,
				{},
				cookies,
				fetch
			);

			if (!editionResponse.ok) {
				if (editionResponse.status === 404) {
					throw error(404, 'Factura no encontrada');
				}
				throw error(editionResponse.status, 'Error al cargar la factura');
			}

			const editionData = await editionResponse.json();
			catalogsData = editionData; // It includes catalogs + invoice
			invoiceData = editionData.invoice;
		}

		// Leyendas fijas (para observaciones)
		try {
			const legendsResponse = await authenticatedFetch(
				`v1/a76/legends/?company_id=${companyId}&page=1&page_size=200`,
				{ method: 'GET' },
				cookies,
				fetch
			);
			if (legendsResponse.ok) {
				legendsData = await legendsResponse.json();
			}
		} catch (e) {
			// No bloquear la carga de factura por fallo en leyendas
			legendsData = { items: [] };
		}

		// Map snake_case response to camelCase props expected by Svelte Page
		// Providing empty arrays as defaults if something is missing
		return {
			invoice: invoiceData,
			invoiceId: params.id === 'new' ? null : parseInt(params.id),
			isCreate: isCreate,
			invoiceTypes: catalogsData.invoice_types || [],
			customsBrokers: catalogsData.customs_brokers || [],
			clients: catalogsData.clients || [],
			providers: catalogsData.providers || [],
			currencyTypes: catalogsData.currency_types || [],
			transportTypes: catalogsData.transport_types || [],
			transporters: catalogsData.transporters || [],
			vehicles: catalogsData.vehicles || [],
			drivers: catalogsData.drivers || [],
			trailers: catalogsData.trailers || [],
			customsSections: catalogsData.customs_sections || [],
			codePedimentoRegimens: catalogsData.code_pedimento_regimens || [],
			seals: catalogsData.seals || [],
			incoterms: catalogsData.incoterms || [],
			valuationMethods: catalogsData.valuation_methods || [],
			pedimentos: catalogsData.pedimentos || [],
			transportModes: catalogsData.transport_modes || [],
			legends: legendsData?.items || [],
			defaultSettings: defaultSettings,
			filters: {
				operation_type: parsedOperationType,
				invoice_type: invoiceTypeParam || null
			}
		};

	} catch (err: any) {
		console.error('Error in load function:', err);
		if (err && typeof err.status === 'number' && [401, 403, 404, 422].includes(err.status)) {
			throw err;
		}
		throw error(500, 'Error interno al cargar la página');
	}
};
