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

const DEFAULT_LIMIT = 20;

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

	// Parse URL parameters
	const customerId = url.searchParams.get('customerId') || null;
	const status = url.searchParams.get('status') || null;
	const page = parseInt(url.searchParams.get('page') || '1', 10);
	const limit = parseInt(url.searchParams.get('limit') || String(DEFAULT_LIMIT), 10);
	const offset = (page - 1) * limit;

	if (!locals.cookie) {
		return {
			invoices: { items: [], totalCount: 0, hasNextPage: false },
			customers: [],
			customerId,
			status,
			page,
			limit
		};
	}

	const client = createServerClient(locals.cookie);

	// Fetch invoices and customers in parallel
	const [invoicesResult, customersResult] = await Promise.all([
		client
			.query<InvoicesQueryResult>({
				query: INVOICES_QUERY,
				variables: {
					filter: {
						customerId: customerId || undefined,
						status: status || undefined
					},
					pagination: {
						offset,
						limit
					}
				}
			})
			.catch((err) => {
				console.error('Failed to fetch invoices:', err);
				return { data: null };
			}),
		client
			.query<CustomersQueryResult>({
				query: CUSTOMERS_QUERY,
				variables: {
					filter: { isActive: true }
				}
			})
			.catch((err) => {
				console.error('Failed to fetch customers:', err);
				return { data: null };
			})
	]);

	return {
		invoices: invoicesResult.data?.invoices ?? { items: [], totalCount: 0, hasNextPage: false },
		customers: customersResult.data?.customers ?? [],
		customerId,
		status,
		page,
		limit
	};
};
