import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getBookById } from '$lib/server/bible';
import {
	composeVerseWindow,
	formatWindowReference
} from '$lib/server/xml-bible';

// Live 3-verse preview for the submission selector. Computes the fall-forward
// window anchored on the selected verse (spec: "Verse Windowing").
export const GET: RequestHandler = async ({ url }) => {
	const bookId = url.searchParams.get('bookId');
	const chapterParam = url.searchParams.get('chapter');
	const verseParam = url.searchParams.get('verse');

	if (!bookId || !chapterParam || !verseParam) {
		return json({ error: 'bookId, chapter, and verse are required' }, { status: 400 });
	}

	const book = getBookById(bookId);
	if (!book) {
		return json({ error: 'Unknown bookId' }, { status: 400 });
	}

	const chapter = Number(chapterParam);
	const verse = Number(verseParam);
	if (!Number.isInteger(chapter) || !Number.isInteger(verse) || chapter < 1 || verse < 1) {
		return json({ error: 'chapter and verse must be positive integers' }, { status: 400 });
	}

	const window = composeVerseWindow(book.order, chapter, verse);
	if (!window) {
		// chapter/verse out of range — caught by composeVerseWindow's bounds checks
		return json({ error: 'chapter or verse out of range for this book' }, { status: 400 });
	}

	const reference = formatWindowReference(
		window.bookName,
		window.startChapter,
		window.startVerse,
		window.endChapter,
		window.endVerse
	);

	return json({
		windowVerses: window.verses,
		reference,
		bookId: window.bookId,
		selectedVerse: window.selectedVerse
	});
};
