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

/**
 * GET /api/ranking
 * Proxies to the Go backend's /api/ranking endpoint.
 * Returns the top-ranked novels list as JSON.
 */
export const GET: RequestHandler = async () => {
	try {
		const res = await backendFetch('/api/ranking');
		if (!res.ok) {
			log.error('api/ranking', 'backend returned error', { status: res.status });
			error(502, `Ranking fetch failed: ${res.status}`);
		}
		const data = await res.json();
		return json(data);
	} catch (e) {
		if (e instanceof Error && 'status' in e) throw e;
		log.error('api/ranking', 'network error', { err: String(e) });
		error(502, 'Could not load ranking');
	}
};
