/**
 * POST /api/scrape/cancel/[id]
 *
 * Admin-only proxy that cancels a pending scrape (or audio) task by ID.
 * Forwards the request to the Go backend POST /api/cancel-task/{id}.
 *
 * Responses:
 *   200  OK       — task cancelled
 *   403  Forbidden — not an admin
 *   409  Conflict  — task cannot be cancelled (already running/done/not found)
 */

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

	const { id } = params;
	if (!id) {
		throw error(400, 'Missing task id');
	}

	let res: Response;
	try {
		res = await backendFetch(`/api/cancel-task/${encodeURIComponent(id)}`, {
			method: 'POST'
		});
	} catch (e) {
		log.error('scrape/cancel', 'network error cancelling task', { id, err: String(e) });
		throw error(502, 'Could not reach backend');
	}

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