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

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

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

	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');
	}

	// Verify the customer owns this invoice
	const customerIds = customers?.map((c: { id: string }) => c.id) ?? [];
	if (!customerIds.includes(invoice.customerId)) {
		throw error(403, 'You do not have access to this invoice');
	}

	return {
		invoice
	};
};
