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

export interface ImageModelInfo {
	id: string;
	label: string;
	provider: string;
	supports_ref: boolean;
	recommended_for: string[]; // "cover" | "chapter"
	description: string;
}

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

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

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

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