/**
 * POST /api/admin/dedup-chapters/[slug]
 *
 * Admin-only proxy to the Go backend's dedup endpoint.
 * Removes duplicate chapters_idx records for a book, keeping the latest
 * record per chapter number. Returns { slug, deleted }.
 */

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 { slug } = params;

	let res: Response;
	try {
		res = await backendFetch(`/api/admin/dedup-chapters/${encodeURIComponent(slug)}`, {
			method: 'POST'
		});
	} catch (e) {
		log.error('admin/dedup-chapters', 'backend proxy error', { slug, err: String(e) });
		throw error(502, 'Could not reach backend');
	}

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