/**
 * POST /api/admin/text-gen/chapter-names/async
 *
 * Fire-and-forget variant: forwards to the Go backend's async endpoint and
 * returns {job_id} immediately (HTTP 202). The backend runs generation in the
 * background; the client polls GET /api/admin/ai-jobs/{id} for progress and
 * then reviews/applies via POST /api/admin/text-gen/chapter-names/apply.
 */

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/text-gen/chapter-names/async', {
			method: 'POST',
			headers: { 'content-type': 'application/json' },
			body
		});
	} catch (e) {
		log.error('admin/text-gen/chapter-names/async', '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 });
};
