import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { bibleBooks } from '$lib/server/bible';
import { getChapterCount, getVerseCount } from '$lib/server/xml-bible';

// Static Bible structure for the cascading Book → Chapter → Verse selectors.
// ~1189 chapter entries total; safe to cache indefinitely.
let cached: { bookId: string; chapters: number[] }[] | null = null;

function build(): { bookId: string; chapters: number[] }[] {
	if (cached) return cached;
	const out = bibleBooks.map((book) => {
		const chapterCount = getChapterCount(book.order);
		const chapters: number[] = new Array(chapterCount);
		for (let c = 1; c <= chapterCount; c++) {
			chapters[c - 1] = getVerseCount(book.order, c);
		}
		return { bookId: book.id, chapters };
	});
	cached = out;
	return out;
}

export const GET: RequestHandler = async () => {
	return json(build());
};
