import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { db } from '$lib/server/db';
import { verseSubmissions, dailyVerses } from '$lib/server/db/schema';
import { eq, desc, asc } from 'drizzle-orm';
import { getCooldownState, todayUtcStr } from '$lib/server/verse-submission';

/**
 * GET /api/submit-verse/status?localDate=YYYY-MM-DD
 *
 * Returns the state needed to render the win-screen submit button:
 * whether the user can submit, the active cooldown (if any), their most
 * recent submission, and their not-yet-reached upcoming submissions.
 */
export const GET: RequestHandler = async ({ locals }) => {
	if (!locals.user) {
		return json({ error: 'Unauthorized' }, { status: 401 });
	}
	const userId = locals.user.id;

	const cooldown = await getCooldownState(db, userId);

	// Most recent submission (by submitted_at) — joined to daily_verses for the
	// canonical reference/window text that will actually play on its day.
	const [lastRow] = await db
		.select({
			scheduledDate: verseSubmissions.scheduledDate,
			reference: dailyVerses.reference
		})
		.from(verseSubmissions)
		.leftJoin(dailyVerses, eq(verseSubmissions.scheduledDate, dailyVerses.date))
		.where(eq(verseSubmissions.userId, userId))
		.orderBy(desc(verseSubmissions.submittedAt))
		.limit(1);

	const lastSubmission = lastRow
		? {
				scheduledDate: lastRow.scheduledDate,
				reference: lastRow.reference
			}
		: null;

	// Upcoming = this user's submissions whose scheduled date hasn't been
	// reached yet (server UTC today).
	const today = todayUtcStr();
	const upcomingRows = await db
		.select({
			scheduledDate: verseSubmissions.scheduledDate,
			reference: dailyVerses.reference
		})
		.from(verseSubmissions)
		.leftJoin(dailyVerses, eq(verseSubmissions.scheduledDate, dailyVerses.date))
		.where(eq(verseSubmissions.userId, userId))
		.orderBy(asc(verseSubmissions.scheduledDate));

	const upcoming = upcomingRows
		.filter((r) => r.scheduledDate > today)
		.map((r) => ({
			scheduledDate: r.scheduledDate,
			reference: r.reference
		}));

	return json({
		canSubmit: !cooldown.onCooldown,
		cooldownEndsAt: cooldown.cooldownEndsAt,
		lastSubmission,
		upcoming
	});
};
