import type { PageServerLoad } from './$types';
import { createServerClient } from '$lib/graphql/client';
import {
	MY_NOTIFICATIONS_QUERY,
	type MyNotificationsQueryResult
} from '$lib/graphql/queries/notifications';
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 unreadOnly = url.searchParams.get('unread') === '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 {
			notifications: [],
			unreadOnly,
			page,
			limit
		};
	}

	const client = createServerClient(locals.cookie);

	try {
		const result = await client.query<MyNotificationsQueryResult>({
			query: MY_NOTIFICATIONS_QUERY,
			variables: {
				unreadOnly,
				limit,
				offset
			}
		});

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