import { AdminNotificationRuleStore, AdminProfilesStore } from '$houdini';
import { error } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async (event) => {
	const { parent } = event;
	const parentData = await parent();
	const me = parentData.user?.data?.me;

	// Gate to ADMIN only
	if (me?.__typename !== 'TeamProfileType' || me.role !== 'ADMIN') {
		throw error(403, 'Admin access required');
	}

	const fetchParams = {
		event,
		metadata: { cookie: event.locals.cookie }
	};

	const [ruleResult, profiles] = await Promise.all([
		new AdminNotificationRuleStore().fetch({
			...fetchParams,
			variables: { id: event.params.rule }
		}),
		new AdminProfilesStore().fetch(fetchParams)
	]);

	if (!ruleResult.data?.notificationRule) {
		throw error(404, 'Notification rule not found');
	}

	return {
		rule: ruleResult,
		profiles
	};
};
