import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { INVOICES_QUERY, type InvoicesQueryResult } from '$lib/graphql/queries/invoices';
import { error } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ locals, parent }) => {
	const { user, customers } = await parent();

	// Must be a customer profile
	if (!user || user.__typename !== 'CustomerProfileType') {
		throw error(403, 'Access denied');
	}

	if (!locals.cookie) {
		return {
			invoices: []
		};
	}

	const client = createServerClient(locals.cookie);

	// Get customer IDs from the customer profile
	const customerIds = customers?.map((c: { id: string }) => c.id) ?? [];

	if (customerIds.length === 0) {
		return {
			invoices: []
		};
	}

	// Fetch invoices for all customer's customers
	// We need to fetch for each customerId since the filter only accepts one
	const invoiceResults = await Promise.all(
		customerIds.map((customerId: string) =>
			client
				.query<InvoicesQueryResult>({
					query: INVOICES_QUERY,
					variables: {
						filter: { customerId },
						pagination: { limit: 100 }
					}
				})
				.catch((err) => {
					console.error(`Failed to fetch invoices for customer ${customerId}:`, err);
					return { data: null };
				})
		)
	);

	// Combine and sort all invoices by endDate descending
	const allInvoices = invoiceResults
		.flatMap((result) => result.data?.invoices?.items ?? [])
		.sort((a, b) => b.endDate.localeCompare(a.endDate));

	return {
		invoices: allInvoices
	};
};
