import type {Crumb} from '@crumbs/core/schemas'

// a crumb's forward date: an explicit plan, else an event start
export const crumbPlannedDate = (c: Crumb): Date | null => {
  const iso =
    (c.status === 'planned' && c.plannedFor) ||
    c.event?.startsAt ||
    null
  return iso ? new Date(iso) : null
}

export const startOfDay = (date: Date): number => {
  const d = new Date(date)
  d.setHours(0, 0, 0, 0)
  return d.getTime()
}

export type UpcomingCrumb = {crumb: Crumb; date: Date}

// dated, not-done crumbs from today onward, soonest first
export const upcomingCrumbs = (crumbs: Crumb[]): UpcomingCrumb[] => {
  const today = startOfDay(new Date())
  return crumbs
    .map((c) => ({crumb: c, date: crumbPlannedDate(c)}))
    .filter(
      (e): e is UpcomingCrumb =>
        e.date != null &&
        e.crumb.status !== 'done' &&
        startOfDay(e.date) >= today,
    )
    .sort((x, y) => x.date.getTime() - y.date.getTime())
}
