import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	WAVE_INVOICES,
	WAVE_PRODUCTS,
	WAVE_CUSTOMERS,
	type WaveInvoiceConnection,
	type WaveProduct,
	type WaveCustomer
} from '$lib/graphql/queries/wave';
import { redirect, error } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ locals, parent, url }) => {
	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);

	// Get pagination params
	const page = parseInt(url.searchParams.get('page') || '1');
	const pageSize = 20;

	// Fetch all Wave data in parallel
	const [invoicesResult, productsResult, customersResult] = await Promise.all([
		client
			.query<{ waveInvoices: WaveInvoiceConnection }>({
				query: WAVE_INVOICES,
				variables: { page, pageSize }
			})
			.catch((err) => {
				console.error('Failed to fetch Wave invoices:', err);
				return { data: null };
			}),
		client
			.query<{ waveProducts: WaveProduct[] }>({
				query: WAVE_PRODUCTS
			})
			.catch((err) => {
				console.error('Failed to fetch Wave products:', err);
				return { data: null };
			}),
		client
			.query<{ waveCustomers: WaveCustomer[] }>({
				query: WAVE_CUSTOMERS
			})
			.catch((err) => {
				console.error('Failed to fetch Wave customers:', err);
				return { data: null };
			})
	]);

	return {
		invoices: invoicesResult.data?.waveInvoices ?? {
			pageInfo: { currentPage: 1, totalPages: 1, totalCount: 0 },
			invoices: []
		},
		products: productsResult.data?.waveProducts ?? [],
		customers: customersResult.data?.waveCustomers ?? [],
		currentPage: page
	};
};
