import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	INVOICE_QUERY,
	ELIGIBLE_REVENUES_QUERY,
	ELIGIBLE_PROJECTS_QUERY,
	type InvoiceQueryResult,
	type EligibleRevenuesQueryResult,
	type EligibleProjectsQueryResult
} from '$lib/graphql/queries/invoices';
import { WAVE_INVOICE_READINESS, type WaveInvoiceReadiness } from '$lib/graphql/queries/wave';
import { redirect, error } from '@sveltejs/kit';

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

	// Redirect if not authenticated or not an admin/team leader
	if (
		!user ||
		user.__typename !== 'TeamProfileType' ||
		(user.role !== 'ADMIN' && user.role !== 'TEAM_LEADER')
	) {
		throw redirect(303, '/');
	}

	if (!locals.cookie) {
		throw error(401, 'Not authenticated');
	}

	const client = createServerClient(locals.cookie);

	// Fetch the invoice
	const invoiceResult = await client
		.query<InvoiceQueryResult>({
			query: INVOICE_QUERY,
			variables: { id: params.invoice }
		})
		.catch((err) => {
			console.error('Failed to fetch invoice:', err);
			return { data: null };
		});

	const invoice = invoiceResult.data?.invoice;

	if (!invoice) {
		throw error(404, 'Invoice not found');
	}

	// Fetch eligible revenues, projects, and Wave readiness in parallel
	const [eligibleRevenuesResult, eligibleProjectsResult, waveReadinessResult] = await Promise.all([
		client
			.query<EligibleRevenuesQueryResult>({
				query: ELIGIBLE_REVENUES_QUERY,
				variables: {
					customerId: invoice.customerId,
					dateFrom: invoice.startDate,
					dateTo: invoice.endDate
				}
			})
			.catch((err) => {
				console.error('Failed to fetch eligible revenues:', err);
				return { data: null };
			}),
		client
			.query<EligibleProjectsQueryResult>({
				query: ELIGIBLE_PROJECTS_QUERY,
				variables: {
					customerId: invoice.customerId,
					dateFrom: invoice.startDate,
					dateTo: invoice.endDate
				}
			})
			.catch((err) => {
				console.error('Failed to fetch eligible projects:', err);
				return { data: null };
			}),
		// Only fetch Wave readiness if not already synced
		invoice.waveInvoiceId
			? Promise.resolve({ data: null })
			: client
					.query<{ waveInvoiceReadiness: WaveInvoiceReadiness }>({
						query: WAVE_INVOICE_READINESS,
						variables: { invoiceId: params.invoice },
						fetchPolicy: 'network-only'
					})
					.catch((err) => {
						console.error('Failed to fetch Wave readiness:', err);
						return { data: null };
					})
	]);

	return {
		invoice,
		eligibleRevenues: eligibleRevenuesResult.data?.eligibleRevenuesForInvoice ?? [],
		eligibleProjects: eligibleProjectsResult.data?.eligibleProjectsForInvoice ?? [],
		waveReadiness: waveReadinessResult.data?.waveInvoiceReadiness ?? null
	};
};
