import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	MY_CONVERSATIONS_QUERY,
	type MyConversationsQueryResult
} from '$lib/graphql/queries/messaging';
import { redirect } from '@sveltejs/kit';

const DEFAULT_LIMIT = 50;

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

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

	// Parse URL parameters
	const includeArchived = url.searchParams.get('archived') === 'true';
	const page = parseInt(url.searchParams.get('page') || '1', 10);
	const limit = parseInt(url.searchParams.get('limit') || String(DEFAULT_LIMIT), 10);
	const offset = (page - 1) * limit;

	if (!locals.cookie) {
		return {
			conversations: [],
			includeArchived,
			page,
			limit
		};
	}

	const client = createServerClient(locals.cookie);

	try {
		const result = await client.query<MyConversationsQueryResult>({
			query: MY_CONVERSATIONS_QUERY,
			variables: {
				includeArchived,
				limit,
				offset
			}
		});

		return {
			conversations: result.data?.myConversations ?? [],
			includeArchived,
			page,
			limit
		};
	} catch (err) {
		console.error('Failed to fetch conversations:', err);
		return {
			conversations: [],
			includeArchived,
			page,
			limit
		};
	}
};
