/**
 * Shared types and helpers for the /api/catalogue backend response.
 *
 * Imported by both:
 *   - src/routes/catalogue/+page.server.ts  (SSR page load)
 *   - src/routes/api/catalogue-page/+server.ts  (infinite-scroll proxy)
 */

/** Shape of a single book as returned by GET /api/catalogue on the Go backend. */
export interface CatalogueBook {
	slug: string;
	title: string;
	author: string;
	cover: string;
	status: string;
	genres: string[];
	summary: string;
	total_chapters: number;
	source_url: string;
	ranking: number;
	rating: number;
}

/** Facets returned alongside catalogue results for dynamic filter options. */
export interface CatalogueFacets {
	genres: string[];
	statuses: string[];
}

/** Full response shape from GET /api/catalogue. */
export interface CatalogueResponse {
	books: CatalogueBook[];
	page: number;
	limit: number;
	total: number;
	has_next: boolean;
	facets?: CatalogueFacets;
}

/** Normalised book shape consumed by the catalogue UI. */
export interface NovelListing {
	slug: string;
	title: string;
	cover: string;
	rank: string;
	rating: string;
	chapters: string;
	url: string;
	// enriched fields
	author?: string;
	status?: string;
	genres?: string[];
	source_url?: string;
}

/** Convert a raw CatalogueBook into the UI NovelListing shape. */
export function bookToListing(book: CatalogueBook): NovelListing {
	return {
		slug: book.slug,
		title: book.title,
		cover: book.cover,
		rank: book.ranking > 0 ? `#${book.ranking}` : '',
		rating: book.rating > 0 ? String(book.rating) : '',
		chapters: book.total_chapters > 0 ? `${book.total_chapters} chapters` : '',
		url: book.source_url ?? '',
		author: book.author,
		status: book.status,
		genres: book.genres ?? [],
		source_url: book.source_url
	};
}
