import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getBook, listChapterIdx, getProgress, isBookSaved } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
import { backendFetch, type BookPreviewResponse } from '$lib/server/scraper';

/**
 * GET /api/book/[slug]
 * Returns book metadata, chapter list, progress, and library status.
 *
 * If the book is not yet in PocketBase, asks the backend to enqueue a scrape
 * task and returns 202 with { scraping: true, task_id }.
 * The client should poll and retry once the task completes.
 */
export const GET: RequestHandler = async ({ params, locals }) => {
	const { slug } = params;

	// Try PocketBase first
	let book = await getBook(slug).catch((e) => {
		log.error('api/book', 'getBook failed', { slug, err: String(e) });
		return null;
	});

	if (book) {
		let chapters, progress, saved;
		try {
			[chapters, progress, saved] = await Promise.all([
				listChapterIdx(slug),
				getProgress(locals.sessionId, slug, locals.user?.id),
				isBookSaved(locals.sessionId, slug, locals.user?.id)
			]);
		} catch (e) {
			log.error('api/book', 'failed to load book detail data', { slug, err: String(e) });
			error(500, 'Failed to load book');
		}

		return json({
			book,
			chapters,
			in_lib: true,
			saved,
			last_chapter: progress?.chapter ?? null,
			scraping: false,
			task_id: null
		});
	}

	// Fall back to backend: enqueue scrape task if not in library.
	try {
		const res = await backendFetch(`/api/book-preview/${encodeURIComponent(slug)}`);

		if (res.status === 202) {
			const body: { task_id: string; message: string } = await res.json();
			log.info('api/book', 'scrape task enqueued', { slug, task_id: body.task_id });
			return json({ scraping: true, task_id: body.task_id, in_lib: false }, { status: 202 });
		}

		if (!res.ok) {
			log.warn('api/book', 'book-preview returned error', { slug, status: res.status });
			error(404, `Book "${slug}" not found`);
		}

		// 200 — book was already in library
		const preview: BookPreviewResponse = await res.json();

		const previewBook = {
			id: '',
			slug: preview.meta.slug || slug,
			title: preview.meta.title,
			author: preview.meta.author,
			cover: preview.meta.cover,
			status: preview.meta.status,
			genres: preview.meta.genres ?? [],
			summary: preview.meta.summary,
			total_chapters: preview.meta.total_chapters,
			source_url: preview.meta.source_url,
			ranking: 0,
			meta_updated: ''
		};

		return json({
			book: previewBook,
			chapters: preview.chapters,
			in_lib: true,
			saved: false,
			last_chapter: null,
			scraping: false,
			task_id: null
		});
	} catch (e) {
		if (e instanceof Error && 'status' in e) throw e;
		log.error('api/book', 'book-preview fetch failed', { slug, err: String(e) });
		error(404, `Book "${slug}" not found`);
	}
};
