/**
 * POST /api/admin/image-gen
 *
 * Admin-only proxy to the Go backend's image generation endpoint.
 * Transparently forwards the request body (JSON or multipart/form-data)
 * and returns the JSON response containing the base64-encoded image.
 */

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 ct = request.headers.get('content-type') ?? '';

	let res: Response;
	try {
		if (ct.includes('multipart/form-data')) {
			// Forward raw body bytes; let the backend parse multipart
			const body = await request.arrayBuffer();
			res = await backendFetch('/api/admin/image-gen', {
				method: 'POST',
				headers: { 'content-type': ct },
				body
			});
		} else {
			const body = await request.text();
			res = await backendFetch('/api/admin/image-gen', {
				method: 'POST',
				headers: { 'content-type': 'application/json' },
				body
			});
		}
	} catch (e) {
		log.error('admin/image-gen', '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 });
};
