import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { WAVE_INVOICE, type WaveInvoice } 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 result = await client
		.query<{ waveInvoice: WaveInvoice }>({
			query: WAVE_INVOICE,
			variables: { invoiceId: params.id }
		})
		.catch((err) => {
			console.error('Failed to fetch Wave invoice:', err);
			return { data: null };
		});

	if (!result.data?.waveInvoice) {
		throw error(404, 'Invoice not found');
	}

	return {
		invoice: result.data.waveInvoice
	};
};
