import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	SERVICE_SCOPE_TEMPLATES_QUERY,
	type ServiceScopeTemplatesQueryResult
} from '$lib/graphql/queries/service-scope-templates';
import {
	PROJECT_SCOPE_TEMPLATES_QUERY,
	type ProjectScopeTemplatesQueryResult
} from '$lib/graphql/queries/project-scope-templates';
import { redirect } from '@sveltejs/kit';

export const load: PageServerLoad = async ({ locals, parent }) => {
	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) {
		return { serviceTemplates: [], projectTemplates: [] };
	}

	const client = createServerClient(locals.cookie);

	try {
		const [serviceResult, projectResult] = await Promise.all([
			client.query<ServiceScopeTemplatesQueryResult>({
				query: SERVICE_SCOPE_TEMPLATES_QUERY,
				fetchPolicy: 'network-only'
			}),
			client.query<ProjectScopeTemplatesQueryResult>({
				query: PROJECT_SCOPE_TEMPLATES_QUERY,
				fetchPolicy: 'network-only'
			})
		]);
		return {
			serviceTemplates: serviceResult.data?.serviceScopeTemplates ?? [],
			projectTemplates: projectResult.data?.projectScopeTemplates ?? []
		};
	} catch (error) {
		console.error('Failed to load scope templates:', error);
		return { serviceTemplates: [], projectTemplates: [] };
	}
};
