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

export const load: PageServerLoad = async ({ fetch, cookies, url, parent }) => {
	const invoiceType = url.searchParams.get('invoice_type');
	const operationType = url.searchParams.get('operation_type');

	if (!operationType) {
		throw redirect(302, '/dashboard');
	}

	// Esperar a que el layout padre valide/refresque el token
	const parentData = await parent();
	
	// Verificar autenticación
	const tokens = getAuthTokens(cookies);
	const accessToken = tokens.accessToken;
	
	if (!accessToken) {
		throw redirect(302, '/auth/login');
	}

	try {
		// Obtener company_id de múltiples fuentes (en orden de prioridad):
		// 1. URL query param (permite cambiar vía navegación)
		// 2. Cookie active_company_id (setted por el team-switcher)
		// 3. Primera compañía del usuario (fallback)
		const companyIdParam = url.searchParams.get('company_id');
		const cookieCompanyId = cookies.get('active_company_id');
		
		const companyId = companyIdParam 
			? parseInt(companyIdParam)
			: cookieCompanyId
				? parseInt(cookieCompanyId)
				: parentData.companies?.[0]?.id;
		
		// Si aún no hay companyId, mostrar error
		if (!companyId) {
			return {
				items: [],
				total: 0,
				page: 1,
				page_size: 50,
				error: 'No se encontró una compañía seleccionada',
				companies: parentData.companies || []
			};
		}
		
		// Construir parámetros de consulta
		const params = new URLSearchParams({
			company_id: companyId.toString(),
			page: '1',
			page_size: '50'
		});
		
		// Agregar filtros opcionales desde query parameters
		const invoiceNumber = url.searchParams.get('invoice_number');
		const projectNumber = url.searchParams.get('project_number');
		const year = url.searchParams.get('year');
		
		if (invoiceType) params.append('invoice_type', invoiceType);
		if (operationType) params.append('operation_type', operationType);
		if (invoiceNumber) params.append('invoice_number', invoiceNumber);
		if (projectNumber) params.append('project_number', projectNumber);
		if (year) params.append('year', year);
		
		// Cargar facturas e invoice types en paralelo
		const [response, invoiceTypesResponse] = await Promise.all([
			authenticatedFetch(
				`v1/a76/invoices?${params.toString()}`,
				{},
				cookies,
				fetch,
				'/auth/login'
			),
			authenticatedFetch(
				'v1/public/reference_data/invoice-types?page=1&page_size=100',
				{},
				cookies,
				fetch,
				'/auth/login'
			)
		]);

		if (!response.ok) {
			return {
				items: [],
				total: 0,
				page: 1,
				page_size: 50,
				error: 'Error al cargar facturas',
				companies: parentData.companies || [],
				currentCompanyId: companyId,
				filters: {
					invoice_type: invoiceType,
					operation_type: operationType
				}
			};
		}

		const data = await response.json();
		const invoiceTypesData = invoiceTypesResponse.ok ? await invoiceTypesResponse.json() : { items: [] };

		return {
			items: data.items || [],
			total: data.total || 0,
			page: data.page || 1,
			page_size: data.page_size || 50,
			companies: parentData.companies || [],
			currentCompanyId: companyId,
			invoiceTypes: invoiceTypesData.items || [],
			filters: {
				invoice_type: invoiceType,
				operation_type: operationType,
				invoice_number: invoiceNumber,
				project_number: projectNumber,
				year: year
			}
		};
	} catch (error) {
		console.error('Error loading invoices:', error);
		if (error instanceof Response && error.status >= 300 && error.status < 400) {
			throw error; // Propagate redirects
		}
		return {
			items: [],
			total: 0,
			page: 1,
			page_size: 50,
			error: 'Error al cargar facturas',
			companies: parentData.companies || []
		};
	}
};
