/**
 * POST /api/admin/catalogue/refresh-metadata/[slug]
 *
 * Admin-only SSE proxy — re-generates description + cover for a single book.
 */
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 ({ params, locals }) => {
	if (!locals.user || locals.user.role !== 'admin') {
		throw error(403, 'Forbidden');
	}
	let res: Response;
	try {
		res = await backendFetch(`/api/admin/catalogue/refresh-metadata/${params.slug}`, {
			method: 'POST',
			headers: { 'content-type': 'application/json' },
			body: '{}'
		});
	} catch (e) {
		log.error('admin/catalogue/refresh-metadata', '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'
		}
	});
};
