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

export const load: PageServerLoad = async ({ params, locals }) => {
	const { slug } = params;

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

	if (book) {
		// Book is in the library — normal path
		let chapters, progress, saved, readersThisWeek, userRating, ratingAvg, currentShelf;
		try {
			[chapters, progress, saved, readersThisWeek, userRating, ratingAvg, currentShelf] = await Promise.all([
				listChapterIdx(slug),
				getProgress(locals.sessionId, slug, locals.user?.id),
				isBookSaved(locals.sessionId, slug, locals.user?.id),
				countReadersThisWeek(slug),
				getBookRating(locals.sessionId, slug, locals.user?.id),
				getBookAvgRating(slug),
				getBookShelf(locals.sessionId, slug, locals.user?.id)
			]);
		} catch (e) {
			log.error('books', 'failed to load book page data', { slug, err: String(e) });
			throw error(500, 'Failed to load book');
		}

		return {
			book,
			chapters,
			inLib: true,
			saved,
			currentShelf: currentShelf ?? '',
			lastChapter: progress?.chapter ?? null,
			readersThisWeek,
			userRating: userRating ?? 0,
			ratingAvg: ratingAvg ?? { avg: 0, count: 0 },
			isAdmin: locals.user?.role === 'admin',
			isLoggedIn: !!locals.user,
			currentUserId: locals.user?.id ?? '',
			// Not scraping
			scraping: false,
			taskId: null as string | null
		};
	}

	// Book not in PocketBase — ask backend to enqueue a scrape task.
	try {
		const res = await backendFetch(`/api/book-preview/${encodeURIComponent(slug)}`);

		if (res.status === 202) {
			// Scrape task enqueued — show "scraping" placeholder page.
			const body: { task_id: string; message: string } = await res.json();
			log.info('books', 'scrape task enqueued for book', { slug, task_id: body.task_id });
			return {
				book: null,
				chapters: [],
				inLib: false,
				saved: false,
				lastChapter: null,
				userRating: 0,
				ratingAvg: { avg: 0, count: 0 },
		isAdmin: locals.user?.role === 'admin',
		isPro: locals.isPro,
		isLoggedIn: !!locals.user,
				currentUserId: locals.user?.id ?? '',
				scraping: true,
				taskId: body.task_id
			};
		}

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

		// 200 — book was already in library when backend checked
		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 {
			book: previewBook,
			chapters: preview.chapters,
			inLib: true,
			saved: false,
			lastChapter: null,
			userRating: 0,
			ratingAvg: { avg: 0, count: 0 },
			isAdmin: locals.user?.role === 'admin',
			isLoggedIn: !!locals.user,
			currentUserId: locals.user?.id ?? '',
			scraping: false,
			taskId: null as string | null
		};
	} catch (e) {
		if (e instanceof Error && 'status' in e) throw e;
		log.error('books', 'book-preview fetch failed', { slug, err: String(e) });
		error(404, `Book "${slug}" not found`);
	}
};
