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

export const GET: RequestHandler = async ({ params, url, locals }) => {
	if (!locals.isPro) {
		error(403, 'EPUB download requires a Pro subscription');
	}

	const { slug } = params;
	const from = url.searchParams.get('from');
	const to = url.searchParams.get('to');

	const qs = new URLSearchParams();
	if (from) qs.set('from', from);
	if (to) qs.set('to', to);
	const query = qs.size ? `?${qs}` : '';

	const res = await backendFetch(`/api/export/${encodeURIComponent(slug)}${query}`);

	if (!res.ok) {
		const text = await res.text().catch(() => '');
		error(res.status as Parameters<typeof error>[0], text || 'Export failed');
	}

	const bytes = await res.arrayBuffer();
	return new Response(bytes, {
		headers: {
			'Content-Type': 'application/epub+zip',
			'Content-Disposition': `attachment; filename="${slug}.epub"`
		}
	});
};
