import { db } from '$lib/server/db';
import { dailyVerses } from '$lib/server/db/schema';
import { eq, sql } from 'drizzle-orm';
import { fetchRandomVerse } from '$lib/server/bible-api';
import type { DailyVerse } from '$lib/server/db/schema';

export async function getVerseForDate(dateStr: string): Promise<DailyVerse> {
	// Validate date format (YYYY-MM-DD)
	if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
		throw new Error('Invalid date format');
	}

	// If there's an existing verse for this date, return it
	const existing = await db.select().from(dailyVerses).where(eq(dailyVerses.date, dateStr)).limit(1);
	if (existing.length > 0) {
		return existing[0];
	}

	// Otherwise get a new random verse for this date
	const apiVerse = await fetchRandomVerse();
	const createdAt = sql`${Math.floor(Date.now() / 1000)}`;

	const newVerse: Omit<DailyVerse, 'createdAt'> = {
		id: Bun.randomUUIDv7(),
		date: dateStr,
		bookId: apiVerse.bookId,
		verseText: apiVerse.verseText,
		reference: apiVerse.reference,
	};

	const [inserted] = await db.insert(dailyVerses).values({ ...newVerse, createdAt }).returning();
	return inserted;
}
