import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';

const SUPPORTED_LANGS = new Set(['ru', 'id', 'pt', 'fr']);

/**
 * POST /api/translation/[slug]/[n]?lang=<lang>
 * Proxy to backend translation enqueue endpoint.
 * Enforces Pro gate — free users cannot enqueue translations.
 *
 * GET /api/translation/[slug]/[n]?lang=<lang>
 * Proxy to backend translation fetch (no gate — already gated at page.server.ts).
 */
export const GET: RequestHandler = async ({ params, url }) => {
	const { slug, n } = params;
	const lang = url.searchParams.get('lang') ?? '';
	const res = await backendFetch(
		`/api/translation/${encodeURIComponent(slug)}/${n}?lang=${lang}`
	);
	if (!res.ok) {
		return new Response(null, { status: res.status });
	}
	const data = await res.json();
	return new Response(JSON.stringify(data), {
		headers: { 'Content-Type': 'application/json' }
	});
};

export const POST: RequestHandler = async ({ params, url, locals }) => {
	const { slug, n } = params;
	const chapter = parseInt(n, 10);
	const lang = url.searchParams.get('lang') ?? '';

	if (!slug || !chapter || chapter < 1) error(400, 'Invalid slug or chapter');
	if (!SUPPORTED_LANGS.has(lang)) error(400, 'Unsupported language');

	// ── Pro gate ──────────────────────────────────────────────────────────────
	if (!locals.isPro) {
		log.info('polar', 'translation blocked for free user', {
			userId: locals.user?.id,
			slug,
			chapter,
			lang
		});
		return new Response(
			JSON.stringify({ error: 'pro_required' }),
			{ status: 402, headers: { 'Content-Type': 'application/json' } }
		);
	}

	const res = await backendFetch(
		`/api/translation/${encodeURIComponent(slug)}/${chapter}?lang=${lang}`,
		{ method: 'POST' }
	);

	if (!res.ok) {
		const text = await res.text().catch(() => '');
		log.error('translation', 'backend translation enqueue failed', { slug, chapter, lang, status: res.status, body: text });
		error(res.status as Parameters<typeof error>[0], text || 'Translation enqueue failed');
	}

	const data = await res.json();
	return new Response(JSON.stringify(data), {
		status: res.status,
		headers: { 'Content-Type': 'application/json' }
	});
};
