import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { redirect, error } from '@sveltejs/kit';
import { CUSTOMER_QUERY, type CustomerQueryResult } from '$lib/graphql/queries/customer';
import { WAVE_CUSTOMERS, type WaveCustomer } from '$lib/graphql/queries/wave';

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

	const [customerResult, waveCustomersResult] = await Promise.all([
		client
			.query<CustomerQueryResult>({
				query: CUSTOMER_QUERY,
				variables: { id: params.customer }
			})
			.catch((err) => {
				console.error('Failed to fetch customer:', err);
				throw error(500, 'Failed to load customer');
			}),
		client
			.query<{ waveCustomers: WaveCustomer[] }>({
				query: WAVE_CUSTOMERS
			})
			.catch((err) => {
				console.error('Failed to fetch Wave customers:', err);
				// Non-fatal: return empty array if Wave fetch fails
				return { data: { waveCustomers: [] } };
			})
	]);

	if (!customerResult.data?.customer) {
		throw error(404, 'Customer not found');
	}

	return {
		customer: customerResult.data.customer,
		contacts: customerResult.data.customer.contacts,
		addresses: customerResult.data.customer.addresses,
		accounts: customerResult.data.customer.accounts,
		waveCustomers: waveCustomersResult.data?.waveCustomers ?? []
	};
};
