/**
 * POST /api/admin/text-gen/chapter-names
 *
 * Admin-only proxy to the Go backend's chapter-name generation endpoint.
 * The backend streams SSE events; this handler pipes the stream through
 * directly so the browser can consume it without buffering.
 */

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

export const POST: RequestHandler = async ({ request, locals }) => {
	if (!locals.user || locals.user.role !== 'admin') {
		throw error(403, 'Forbidden');
	}

	const body = await request.text();
	let res: Response;
	try {
		res = await backendFetch('/api/admin/text-gen/chapter-names', {
			method: 'POST',
			headers: { 'content-type': 'application/json' },
			body
		});
	} catch (e) {
		log.error('admin/text-gen/chapter-names', 'backend proxy error', { err: String(e) });
		throw error(502, 'Could not reach backend');
	}

	// Non-2xx: the backend returned a JSON error before switching to SSE.
	if (!res.ok) {
		const data = await res.json().catch(() => ({}));
		return new Response(JSON.stringify(data), {
			status: res.status,
			headers: { 'Content-Type': 'application/json' }
		});
	}

	// Pipe the SSE stream straight through — do not buffer.
	return new Response(res.body, {
		status: 200,
		headers: {
			'Content-Type': 'text/event-stream',
			'Cache-Control': 'no-cache',
			'X-Accel-Buffering': 'no'
		}
	});
};
