import { startOfLocalDay } from "@/lib/utils";

function toLocalDateKey(date: Date): string {
  const year = date.getFullYear();
  const month = `${date.getMonth() + 1}`.padStart(2, "0");
  const day = `${date.getDate()}`.padStart(2, "0");
  return `${year}-${month}-${day}`;
}

export function getHabitStreak(
  completedDates: string[],
  options?: {
    maxDays?: number;
    today?: Date;
  },
): number {
  const uniqueDates = new Set(completedDates);
  const today = startOfLocalDay(options?.today ?? new Date());
  const maxDays = options?.maxDays ?? 365;

  let streak = 0;

  for (let dayOffset = 0; dayOffset < maxDays; dayOffset += 1) {
    const currentDay = new Date(today);
    currentDay.setDate(currentDay.getDate() - dayOffset);
    const currentDateKey = toLocalDateKey(currentDay);

    if (uniqueDates.has(currentDateKey)) {
      streak += 1;
      continue;
    }

    if (dayOffset > 0) {
      break;
    }
  }

  return streak;
}
