import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import { CONVERSATION_QUERY, type ConversationQueryResult } from '$lib/graphql/queries/messaging';
import { TEAM_PROFILES_QUERY, type TeamProfilesQueryResult } from '$lib/graphql/queries/team';
import { redirect, error } from '@sveltejs/kit';

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

	// Redirect if not authenticated
	if (!user) {
		throw redirect(303, '/login');
	}

	if (!locals.cookie) {
		throw error(500, 'Not authenticated');
	}

	const client = createServerClient(locals.cookie);

	try {
		const [conversationResult, teamResult] = await Promise.all([
			client.query<ConversationQueryResult>({
				query: CONVERSATION_QUERY,
				variables: { id: params.conversation }
			}),
			// Fetch team profiles for adding participants
			client
				.query<TeamProfilesQueryResult>({
					query: TEAM_PROFILES_QUERY,
					variables: { filter: { isActive: true } }
				})
				.catch(() => ({ data: null }))
		]);

		if (!conversationResult.data?.conversation) {
			throw error(404, 'Conversation not found');
		}

		return {
			conversation: conversationResult.data.conversation,
			teamProfiles: teamResult.data?.teamProfiles ?? []
		};
	} catch (err) {
		console.error('Failed to fetch conversation:', err);
		throw error(500, 'Failed to load conversation');
	}
};
