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

/**
 * GET /api/chapter-text-preview/[slug]/[n]
 * Proxies to the backend's /api/chapter-text-preview endpoint.
 * Used client-side when the normal chapter path returns no content
 * (chapter indexed but not yet scraped to MinIO).
 */
export const GET: RequestHandler = async ({ params, url }) => {
	const { slug, n } = params;
	const chapter = parseInt(n, 10);
	if (!slug || !chapter || chapter < 1) {
		error(400, 'Invalid slug or chapter number');
	}

	// Forward optional query params (chapter_url, title) if present
	const qs = new URLSearchParams();
	const chapterUrl = url.searchParams.get('chapter_url');
	const title = url.searchParams.get('title');
	if (chapterUrl) qs.set('chapter_url', chapterUrl);
	if (title) qs.set('title', title);

	const scraperRes = await backendFetch(
		`/api/chapter-text-preview/${encodeURIComponent(slug)}/${chapter}?${qs.toString()}`
	).catch((e) => {
		log.error('chapter-preview', 'scraper fetch failed', { slug, chapter, err: String(e) });
		return null;
	});

	if (!scraperRes || !scraperRes.ok) {
		const status = scraperRes?.status ?? 502;
		log.error('chapter-preview', 'scraper returned error', { slug, chapter, status });
		error(status as Parameters<typeof error>[0], 'Chapter preview not available');
	}

	const data = await scraperRes.json();

	return new Response(JSON.stringify(data), {
		headers: { 'Content-Type': 'application/json' }
	});
};
