import { parseSprintEnd, parseSprintStart } from "@/lib/server/sprintState"

export interface SprintLike {
  id: string;
  startDate: string;
  endDate: string;
}

export function isSprintInProgress(startDate: string, endDate: string, now: Date = new Date()): boolean {
  const sprintStart = parseSprintStart(startDate)
  const sprintEnd = parseSprintEnd(endDate)
  return sprintStart <= now && sprintEnd >= now
}

export function findCurrentSprint<T extends SprintLike>(
  sprints: T[],
  options?: {
    now?: Date
  }
): T | null {
  const now = options?.now ?? new Date()
  const inProgress = sprints.filter((s) => isSprintInProgress(s.startDate, s.endDate, now))

  if (inProgress.length === 0) return null

  // When date windows overlap, select the most recently started sprint.
  return inProgress
    .slice()
    .sort((a, b) => {
      const startDelta = parseSprintStart(b.startDate).getTime() - parseSprintStart(a.startDate).getTime()
      if (startDelta !== 0) return startDelta
      return parseSprintEnd(a.endDate).getTime() - parseSprintEnd(b.endDate).getTime()
    })[0]
}
