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
	if (!user) {
		throw redirect(303, '/login');
	}

	// Check if user is admin (can message customers)
	const isAdmin = user.__typename === 'TeamProfileType' && user.role === 'ADMIN';
	const isCustomer = user.__typename === 'CustomerProfileType';

	// Parse URL params for pre-filling the form
	const prefill = {
		subject: url.searchParams.get('subject') ?? undefined,
		entityType: url.searchParams.get('entityType') ?? undefined,
		entityId: url.searchParams.get('entityId') ?? undefined,
		participants: url.searchParams.get('participants')?.split(',').filter(Boolean) ?? []
	};

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

	const client = createServerClient(locals.cookie);

	try {
		// Fetch team profiles for recipient selection
		const teamResult = await client.query<TeamProfilesQueryResult>({
			query: TEAM_PROFILES_QUERY
		});

		// Fetch customer profiles if admin
		let customerProfiles: CustomerProfilesQueryResult['customerProfiles'] = [];
		if (isAdmin) {
			const customerResult = await client.query<CustomerProfilesQueryResult>({
				query: CUSTOMER_PROFILES_QUERY
			});
			customerProfiles = customerResult.data?.customerProfiles ?? [];
		}

		// Filter team profiles to only admins if user is a customer
		let teamProfiles = teamResult.data?.teamProfiles ?? [];
		if (isCustomer) {
			teamProfiles = teamProfiles.filter((p) => p.role === 'ADMIN');
		}

		return {
			teamProfiles,
			customerProfiles,
			isAdmin,
			prefill
		};
	} catch (err) {
		console.error('Failed to fetch profiles:', err);
		return {
			teamProfiles: [],
			customerProfiles: [],
			isAdmin,
			prefill
		};
	}
};
