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

export const load: PageServerLoad = async ({ locals, parent, url }) => {
	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, '/');
	}

	// Get active tab from URL params (default to 'team')
	const tab = url.searchParams.get('tab') || 'team';

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

	const client = createServerClient(locals.cookie);

	// Fetch both profile types in parallel
	const [teamResult, customerResult] = await Promise.all([
		client
			.query<TeamProfilesQueryResult>({
				query: TEAM_PROFILES_QUERY
			})
			.catch((err) => {
				console.error('Failed to fetch team profiles:', err);
				return { data: null };
			}),
		client
			.query<CustomerProfilesQueryResult>({
				query: CUSTOMER_PROFILES_QUERY
			})
			.catch((err) => {
				console.error('Failed to fetch customer profiles:', err);
				return { data: null };
			})
	]);

	return {
		teamProfiles: teamResult.data?.teamProfiles ?? [],
		customerProfiles: customerResult.data?.customerProfiles ?? [],
		tab
	};
};
