import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { db } from '$lib/server/db';
import { dailyCompletions } from '$lib/server/db/schema';
import { eq, desc } from 'drizzle-orm';

export const GET: RequestHandler = async ({ url }) => {
	const anonymousId = url.searchParams.get('anonymousId');
	const localDate = url.searchParams.get('localDate');

	if (!anonymousId || !localDate) {
		error(400, 'Missing anonymousId or localDate');
	}

	// Fetch all completion dates for this user (stored as the user's local date)
	const rows = await db
		.select({ date: dailyCompletions.date })
		.from(dailyCompletions)
		.where(eq(dailyCompletions.anonymousId, anonymousId))
		.orderBy(desc(dailyCompletions.date));

	const completedDates = new Set(rows.map((r) => r.date));

	// Subtract one calendar day from a YYYY-MM-DD string using UTC arithmetic —
	// this avoids any dependence on the server's local timezone or DST offsets.
	function prevDay(dateStr: string): string {
		const d = new Date(dateStr + 'T00:00:00Z');
		d.setUTCDate(d.getUTCDate() - 1);
		return d.toISOString().slice(0, 10);
	}

	// Walk backwards from the user's local date, counting consecutive completed days
	let streak = 0;
	let cursor = localDate;

	while (completedDates.has(cursor)) {
		streak++;
		cursor = prevDay(cursor);
	}

	return json({ streak: streak < 2 ? 0 : streak });
};
