import type { PageServerLoad } from './$types';
import { listTextModels } from '$lib/server/scraper';
import { log } from '$lib/server/logger';
import { listBooks } from '$lib/server/pocketbase';

export interface BookSummary {
	slug: string;
	title: string;
}

export interface TextModelInfo {
	id: string;
	label: string;
	provider: string;
	context_size: number;
	description: string;
}

export const load: PageServerLoad = async () => {
	// Parent layout already guards admin role.
	const [models, booksResult] = await Promise.allSettled([
		listTextModels<TextModelInfo>(),
		listBooks()
	]);

	if (models.status === 'rejected') {
		log.warn('admin/text-gen', 'failed to load models', { err: String(models.reason) });
	}

	return {
		models: models.status === 'fulfilled' ? models.value : ([] as TextModelInfo[]),
		books: (booksResult.status === 'fulfilled' ? booksResult.value : []).map((b) => ({
			slug: b.slug,
			title: b.title
		})) as BookSummary[]
	};
};
