import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';
import { bookToListing, type CatalogueResponse } from '$lib/server/catalogue';

/**
 * GET /api/catalogue-page?page=2&genre=all&sort=popular&status=all&q=
 *
 * Thin proxy to the Go backend's /api/catalogue endpoint.
 * Used by the infinite-scroll catalogue page to append subsequent pages
 * without a full SSR navigation.
 *
 * Returns { novels, page, hasNext } — the shape expected by the client-side
 * infinite scroll in +page.svelte.
 */
export const GET: RequestHandler = async ({ url }) => {
	const page = url.searchParams.get('page') ?? '1';
	const genre = url.searchParams.get('genre') ?? 'all';
	const sort = url.searchParams.get('sort') ?? 'popular';
	const status = url.searchParams.get('status') ?? 'all';
	const q = url.searchParams.get('q') ?? '';

	const params = new URLSearchParams({ page, genre, sort, status });
	if (q.trim().length >= 2) {
		params.set('q', q.trim());
	}

	try {
		const res = await backendFetch(`/api/catalogue?${params.toString()}`);
		if (!res.ok) {
			log.error('catalogue-page', 'backend returned error', { status: res.status });
			throw error(502, `Catalogue fetch failed: ${res.status}`);
		}
		const data: CatalogueResponse = await res.json();

		return json({
			novels: (data.books ?? []).map(bookToListing),
			page: data.page ?? (parseInt(page, 10) || 1),
			hasNext: data.has_next ?? false
		});
	} catch (e) {
		if (e instanceof Error && 'status' in e) throw e;
		log.error('catalogue-page', 'network error', { err: String(e) });
		throw error(502, 'Could not reach catalogue service');
	}
};
