import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	NOTIFICATION_RULES_QUERY,
	type NotificationRulesQueryResult
} from '$lib/graphql/queries/notifications';
import { TEAM_PROFILES_QUERY, type TeamProfilesQueryResult } from '$lib/graphql/queries/team';
import { redirect } from '@sveltejs/kit';

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

	// Redirect if not authenticated or not an admin
	if (!user || user.__typename !== 'TeamProfileType' || user.role !== 'ADMIN') {
		throw redirect(303, '/');
	}

	if (!locals.cookie) {
		return {
			rules: [],
			teamProfiles: []
		};
	}

	const client = createServerClient(locals.cookie);

	try {
		const [rulesResult, teamResult] = await Promise.all([
			client.query<NotificationRulesQueryResult>({
				query: NOTIFICATION_RULES_QUERY
			}),
			client
				.query<TeamProfilesQueryResult>({
					query: TEAM_PROFILES_QUERY
				})
				.catch(() => ({ data: null }))
		]);

		return {
			rules: rulesResult.data?.notificationRules ?? [],
			teamProfiles: teamResult.data?.teamProfiles ?? []
		};
	} catch (err) {
		console.error('Failed to fetch notification rules:', err);
		return {
			rules: [],
			teamProfiles: []
		};
	}
};
