/**
 * POST /api/admin/image-gen/save-chapter-image
 *
 * Admin-only proxy: persists a pre-generated base64 image as a chapter
 * illustration in MinIO without re-calling Cloudflare AI.
 *
 * Body: { slug: string, chapter: number, image_b64: string }
 */

import { json, 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/image-gen/save-chapter-image', {
			method: 'POST',
			headers: { 'content-type': 'application/json' },
			body
		});
	} catch (e) {
		log.error('admin/image-gen/save-chapter-image', 'backend proxy error', { err: String(e) });
		throw error(502, 'Could not reach backend');
	}

	const data = await res.json().catch(() => ({}));
	return json(data, { status: res.status });
};
