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

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

	const client = createServerClient(locals.cookie);

	try {
		const { data } = await client.query<CustomersQueryResult>({
			query: CUSTOMERS_QUERY,
			variables: { filter: null }
		});
		return { customers: data?.customers ?? [] };
	} catch (error) {
		console.error('Failed to fetch customers:', error);
		return { customers: [] };
	}
};
