import type { DailyVerse } from '$lib/server/db/schema';
import { getBookById } from './bible';
import { getRandomVerses, formatReference } from './xml-bible';

type ApiVerse = Omit<DailyVerse, 'id' | 'date' | 'createdAt'>;

export async function fetchRandomVerse(): Promise<ApiVerse> {
	// Get 3 random verses from the local XML Bible
	const verseData = getRandomVerses(3);

	if (!verseData) {
		throw new Error('Failed to get random verses from Bible XML');
	}

	const { bookId, bookName, chapter, startVerse, endVerse, verses } = verseData;

	// Validate bookId
	if (!getBookById(bookId)) {
		throw new Error(`Unknown book ID: ${bookId}`);
	}

	// Format the reference string (e.g., "Matthew 1:1-3")
	const reference = formatReference(bookName, chapter, startVerse, endVerse);

	// Join verses with spaces
	const verseText = verses.join(' ');

	return {
		bookId,
		reference,
		verseText
	};
}
