import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
	getBooksBySlugs,
	recentlyAddedBooks,
	allProgress,
	getHomeStats,
	getSubscriptionFeed
} from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
import type { Book, Progress } from '$lib/server/pocketbase';

/**
 * GET /api/home
 * Returns home screen data: continue-reading list, recently updated books, stats,
 * and subscription feed (books recently read by followed users).
 * Requires authentication (enforced by layout guard).
 */
export const GET: RequestHandler = async ({ locals }) => {
	let recentBooks: Book[] = [];
	let progressList: Progress[] = [];
	let stats = { totalBooks: 0, totalChapters: 0 };

	try {
		[recentBooks, progressList, stats] = await Promise.all([
			recentlyAddedBooks(8),
			allProgress(locals.sessionId, locals.user?.id),
			getHomeStats()
		]);
	} catch (e) {
		log.error('api/home', 'failed to load home data', { err: String(e) });
	}

	// Fetch only the books we actually need for continue-reading.
	const progressSlugs = progressList.map((p) => p.slug);
	const progressBooks = progressSlugs.length > 0
		? await getBooksBySlugs(progressSlugs).catch(() => [] as Book[])
		: [];

	const bookMap = new Map<string, Book>(progressBooks.map((b) => [b.slug, b]));

	const continueReading = progressList
		.filter((p) => bookMap.has(p.slug))
		.slice(0, 6)
		.map((p) => ({ book: bookMap.get(p.slug)!, chapter: p.chapter }));

	const inProgressSlugs = new Set(continueReading.map((c) => c.book.slug));
	const recentlyUpdated = recentBooks.filter((b) => !inProgressSlugs.has(b.slug)).slice(0, 6);

	// Subscription feed — only available for logged-in users with following
	let subscriptionFeed: Array<{ book: Book; readerUsername: string }> = [];
	if (locals.user?.id) {
		subscriptionFeed = await getSubscriptionFeed(locals.user.id).catch(() => []);
	}

	return json({
		continue_reading: continueReading,
		recently_updated: recentlyUpdated,
		stats: {
			totalBooks: stats.totalBooks,
			totalChapters: stats.totalChapters,
			booksInProgress: continueReading.length
		},
		subscription_feed: subscriptionFeed.map((item) => ({
			book: item.book,
			readerUsername: item.readerUsername
		}))
	});
};
