import {
	MeStore as User,
	TeamStore as Team,
	CustomersStore as Customers,
	AccountsBasicStore as Accounts
} from '$houdini';
import type { LayoutServerLoad } from './$types';
import {
	buildAccountAddressLookup,
	buildCustomerLookup,
	buildNonAdminTeamIds,
	buildTeamMemberLookup
} from '$lib/utils/lookup';

export const load: LayoutServerLoad = async (event) => {
	const fetchParams = {
		event,
		metadata: { cookie: event.locals.cookie }
	};

	const [user, team, customers, accounts] = await Promise.all([
		new User().fetch(fetchParams),
		new Team().fetch(fetchParams),
		new Customers().fetch(fetchParams),
		new Accounts().fetch(fetchParams)
	]);

	// Build lookups once at the root level
	const accountLookup = buildAccountAddressLookup(accounts?.data?.accounts);
	const customerLookup = buildCustomerLookup(customers?.data?.customers);
	const nonAdminTeamIds = buildNonAdminTeamIds(team?.data?.teamProfiles);
	const teamMemberLookup = buildTeamMemberLookup(team?.data?.teamProfiles);

	return {
		user,
		team,
		customers,
		accounts,
		accountLookup,
		customerLookup,
		nonAdminTeamIds,
		teamMemberLookup
	};
};
