import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { redirect, error } from '@sveltejs/kit';
import { ACCOUNT_QUERY, type AccountQueryResult } from '$lib/graphql/queries/account';
import { WAVE_PRODUCTS, type WaveProduct } 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 [accountResult, waveProductsResult] = await Promise.all([
		client
			.query<AccountQueryResult>({
				query: ACCOUNT_QUERY,
				variables: { id: params.account }
			})
			.catch((err) => {
				console.error('Failed to fetch account:', err);
				throw error(500, 'Failed to load account');
			}),
		client
			.query<{ waveProducts: WaveProduct[] }>({
				query: WAVE_PRODUCTS
			})
			.catch((err) => {
				console.error('Failed to fetch wave products:', err);
				return { data: null };
			})
	]);

	if (!accountResult.data?.account) {
		throw error(404, 'Account not found');
	}

	return {
		account: accountResult.data.account,
		contacts: accountResult.data.account.contacts,
		addresses: accountResult.data.account.addresses,
		revenues: accountResult.data.account.revenues,
		waveProducts: waveProductsResult.data?.waveProducts ?? []
	};
};
