/**
 * POST /api/admin/catalogue/batch-covers
 *
 * Admin-only SSE proxy to the Go backend's batch cover generation endpoint.
 * Pipes the stream straight through 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/catalogue/batch-covers', {
			method: 'POST',
			headers: { 'content-type': 'application/json' },
			body
		});
	} catch (e) {
		log.error('admin/catalogue/batch-covers', 'backend proxy error', { err: String(e) });
		throw error(502, 'Could not reach backend');
	}
	if (!res.ok) {
		const data = await res.json().catch(() => ({}));
		return new Response(JSON.stringify(data), {
			status: res.status,
			headers: { 'Content-Type': 'application/json' }
		});
	}
	return new Response(res.body, {
		status: 200,
		headers: {
			'Content-Type': 'text/event-stream',
			'Cache-Control': 'no-cache',
			'X-Accel-Buffering': 'no'
		}
	});
};
