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

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

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

    const companyId = await getActiveCompanyId(cookies, fetch);
    if (!companyId) {
        throw error(400, 'No se encontró una compañía seleccionada');
    }

    // Load necessary reference data for the settings form
    // We need: InvoiceTypes, CustomsBrokers, Incoterms, etc. to populate the reusable forms

    // We load minimal data initially, but to support all tabs we need more.
    // Reuse the same calls as in edit/[id] to ensure we have data for the dropdowns

    const invoiceTypesPromise = authenticatedFetch(
        'v1/public/reference_data/invoice-types/?page=1&page_size=100',
        {},
        cookies,
        fetch
    );

    const customsBrokersPromise = authenticatedFetch(
        `v1/a76/customs-brokers/?company_id=${companyId}&page=1&page_size=100`,
        {},
        cookies,
        fetch
    );

    const clientsPromise = authenticatedFetch(
        `v1/a76/clients-providers/?company_id=${companyId}&type=client&page=1&page_size=1000`,
        {},
        cookies,
        fetch
    );

    const providersPromise = authenticatedFetch(
        `v1/a76/clients-providers/?company_id=${companyId}&type=provider&page=1&page_size=1000`,
        {},
        cookies,
        fetch
    );

    const currencyTypesPromise = authenticatedFetch(
        'v1/public/reference_data/currency-types/?page=1&page_size=100',
        {},
        cookies,
        fetch
    );

    const transportTypesPromise = authenticatedFetch(
        'v1/public/reference_data/transport-types/?page=1&page_size=100',
        {},
        cookies,
        fetch
    );

    const transportersPromise = authenticatedFetch(
        `v1/a76/transportation/transporters/?company_id=${companyId}&page=1&page_size=100`,
        {},
        cookies,
        fetch
    );

    const vehiclesPromise = authenticatedFetch(
        `v1/a76/transportation/vehicles/?company_id=${companyId}&page=1&page_size=100`,
        {},
        cookies,
        fetch
    );

    const driversPromise = authenticatedFetch(
        `v1/a76/transportation/drivers/?company_id=${companyId}`,
        {},
        cookies,
        fetch
    );

    const trailersPromise = authenticatedFetch(
        `v1/a76/transportation/trailers/?company_id=${companyId}&page=1&page_size=100`,
        {},
        cookies,
        fetch
    );

    const incotermsPromise = authenticatedFetch(
        'v1/public/reference_data/incoterms/?page=1&page_size=100',
        {},
        cookies,
        fetch
    );

    const customsSectionsPromise = authenticatedFetch(
        'v1/public/reference_data/customs-sections/?page=1&page_size=100',
        {},
        cookies,
        fetch
    );

    const codePedimentoRegimensPromise = authenticatedFetch(
        'v1/public/reference_data/code-pedimento-regimens/?page=1&page_size=1000',
        {},
        cookies,
        fetch
    );

    const transportModesPromise = authenticatedFetch(
        'v1/public/reference_data/transport-modes/?page=1&page_size=100',
        {},
        cookies,
        fetch
    );

    const valuationMethodsPromise = authenticatedFetch(
        'v1/public/reference_data/valuation-methods/?page=1&page_size=100',
        {},
        cookies,
        fetch
    );

    const legendsPromise = authenticatedFetch(
        `v1/a76/legends/?company_id=${companyId}&page=1&page_size=200`,
        {},
        cookies,
        fetch
    );

    const sealsPromise = authenticatedFetch(
        `v1/a76/seals/?company_id=${companyId}&page=1&page_size=100`,
        {},
        cookies,
        fetch
    );

    const enclosuresPromise = authenticatedFetch(
        'v1/public/reference_data/customs-warehouses/?page=1&page_size=100',
        {},
        cookies,
        fetch
    );

    const pedimentosPromise = authenticatedFetch(
        `v1/a76/pedimentos/?company_id=${companyId}&page=1&page_size=100`,
        {},
        cookies,
        fetch
    );

    try {
        const [
            invoiceTypesResponse,
            customsBrokersResponse,
            clientsResponse,
            providersResponse,
            currencyTypesResponse,
            transportTypesResponse,
            transportersResponse,
            vehiclesResponse,
            driversResponse,
            trailersResponse,
            incotermsResponse,
            customsSectionsResponse,
            codePedimentoRegimensResponse,
            transportModesResponse,
            valuationMethodsResponse,
            legendsResponse,
            sealsResponse,
            enclosuresResponse,
            pedimentosResponse
        ] = await Promise.all([
            invoiceTypesPromise,
            customsBrokersPromise,
            clientsPromise,
            providersPromise,
            currencyTypesPromise,
            transportTypesPromise,
            transportersPromise,
            vehiclesPromise,
            driversPromise,
            trailersPromise,
            incotermsPromise,
            customsSectionsPromise,
            codePedimentoRegimensPromise,
            transportModesPromise,
            valuationMethodsPromise,
            legendsPromise,
            sealsPromise,
            enclosuresPromise,
            pedimentosPromise
        ]);

        const invoiceTypes = invoiceTypesResponse.ok ? await invoiceTypesResponse.json() : { items: [] };
        const customsBrokers = customsBrokersResponse.ok ? await customsBrokersResponse.json() : { items: [] };
        const clients = clientsResponse.ok ? await clientsResponse.json() : { items: [] };
        const providers = providersResponse.ok ? await providersResponse.json() : { items: [] };
        const currencyTypes = currencyTypesResponse.ok ? await currencyTypesResponse.json() : { items: [] };
        const transportTypes = transportTypesResponse.ok ? await transportTypesResponse.json() : { items: [] };
        const transporters = transportersResponse.ok ? await transportersResponse.json() : { items: [] };
        const vehicles = vehiclesResponse.ok ? await vehiclesResponse.json() : { items: [] };
        const drivers = driversResponse.ok ? await driversResponse.json() : { items: [] };
        const trailers = trailersResponse.ok ? await trailersResponse.json() : { items: [] };
        const incoterms = incotermsResponse.ok ? await incotermsResponse.json() : { items: [] };
        const customsSections = customsSectionsResponse.ok ? await customsSectionsResponse.json() : { items: [] };
        const codePedimentoRegimens = codePedimentoRegimensResponse.ok ? await codePedimentoRegimensResponse.json() : { items: [] };
        const transportModes = transportModesResponse.ok ? await transportModesResponse.json() : { items: [] };
        const valuationMethods = valuationMethodsResponse.ok ? await valuationMethodsResponse.json() : { items: [] };
        const legends = legendsResponse.ok ? await legendsResponse.json() : { items: [] };
        const seals = sealsResponse.ok ? await sealsResponse.json() : { items: [] };
        const enclosures = enclosuresResponse.ok ? await enclosuresResponse.json() : { items: [] };
        const pedimentos = pedimentosResponse.ok ? await pedimentosResponse.json() : { items: [] };

        return {
            invoiceTypes: invoiceTypes.items || [],
            customsBrokers: customsBrokers.items || [],
            clients: clients.items || [],
            providers: providers.items || [],
            currencyTypes: currencyTypes.items || [],
            transportTypes: transportTypes.items || [],
            transporters: transporters.items || [],
            vehicles: vehicles.items || [],
            drivers: drivers.items || [],
            trailers: trailers.items || [],
            incoterms: incoterms.items || [],
            customsSections: customsSections.items || [],
            codePedimentoRegimens: codePedimentoRegimens.items || [],
            transportModes: transportModes.items || [],
            valuationMethods: valuationMethods.items || [],
            legends: legends.items || [],
            seals: seals.items || [],
            enclosure: enclosures.items || [],
            pedimentos: pedimentos.items || [],
            companyId
        };

    } catch (err) {
        console.error('Error loading settings data:', err);
        return {
            invoiceTypes: [],
            customsBrokers: [],
            incoterms: [],
            customsSections: [],
            companyId
        };
    }
};
