import type { PageServerLoad } from './$types';
import { error } from '@sveltejs/kit';
import { getRandomGreekVerses, extractVerses, formatReference } from '$lib/server/xml-bible';
import { getBookById, bookIdToNumber } from '$lib/server/bible';

export const load: PageServerLoad = async () => {
	const greekData = getRandomGreekVerses(3);

	if (!greekData) {
		throw error(500, 'Failed to load Greek verses');
	}

	const bookNumber = bookIdToNumber[greekData.bookId];
	const englishVerses = extractVerses(bookNumber, greekData.chapter, greekData.startVerse, 3);
	const reference = formatReference(greekData.bookName, greekData.chapter, greekData.startVerse, greekData.endVerse);
	const greekVerseText = greekData.verses.join(' ');
	const englishVerseText = englishVerses.join(' ');

	const dailyVerse = {
		id: 'greek-random-' + Date.now(),
		date: new Date().toLocaleDateString('en-CA', { timeZone: 'America/New_York' }),
		bookId: greekData.bookId,
		reference,
		verseText: englishVerseText,
		createdAt: new Date()
	};

	const correctBook = getBookById(dailyVerse.bookId) ?? null;

	return {
		dailyVerse,
		greekVerseText,
		reference,
		correctBookId: dailyVerse.bookId,
		correctBook
	};
};