/**
 * GET /api/admin/ai-jobs/[id]
 *
 * Admin-only proxy to the Go backend's AI job detail endpoint.
 * Returns the full job record including the payload field (which contains
 * results for completed chapter-names jobs).
 */

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 GET: RequestHandler = async ({ params, locals }) => {
	if (!locals.user || locals.user.role !== 'admin') {
		throw error(403, 'Forbidden');
	}

	const { id } = params;

	let res: Response;
	try {
		res = await backendFetch(`/api/admin/ai-jobs/${id}`, { method: 'GET' });
	} catch (e) {
		log.error('admin/ai-jobs/get', 'backend proxy error', { id, err: String(e) });
		throw error(502, 'Could not reach backend');
	}

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