import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { error } from '@sveltejs/kit';
import { ACCOUNT_QUERY, type AccountQueryResult } from '$lib/graphql/queries/account';

export const load: PageServerLoad = async ({ locals, parent, params }) => {
	const { user, accounts } = await parent();

	// Verify the account belongs to one of the assigned customers
	const assignedAccountIds = accounts?.map((a: { id: string }) => a.id) ?? [];
	if (!assignedAccountIds.includes(params.account)) {
		throw error(403, 'You do not have access to this account');
	}

	if (!locals.cookie) {
		throw error(401, 'Not authenticated');
	}

	const client = createServerClient(locals.cookie);

	const { data } = await 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');
		});

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

	return {
		account: data.account,
		contacts: data.account.contacts,
		addresses: data.account.addresses
	};
};
