import {
  addDays,
  dateOf,
  isoDayOfWeek,
  lastDayOfMonth,
  monthOf,
} from "@/lib/calendar"

/**
 * Which days My Tasks shows.
 *
 * Its own module, with nothing under it but `lib/calendar.ts`, because the view
 * switcher is a client component. Taking `VIEWS` from the service that queries
 * tasks pulled `lib/db/client.ts` into the browser bundle, and the build failed
 * on `Can't resolve 'tls'` from inside the Postgres driver. That is the third
 * time this repository has drawn that line, after `lib/levels.ts` and
 * `lib/choice.ts`: a client component may take types from anywhere and values
 * only from here.
 */

export type View = "day" | "week" | "month"

export const VIEWS: View[] = ["day", "week", "month"]

export function isView(value: unknown): value is View {
  return typeof value === "string" && (VIEWS as string[]).includes(value)
}

/**
 * The window a view draws, as two Bangkok calendar days, inclusive at both
 * ends. Strings in and strings out, like everything else that touches a day.
 *
 * The week runs Monday to Sunday, which is the ISO numbering the schedules are
 * already written in, so a weekly duty on day 1 lands on the first day of the
 * week somebody is looking at rather than the second.
 */
export function windowFor(
  view: View,
  today: string,
): { from: string; to: string } {
  if (view === "day") return { from: today, to: today }

  if (view === "week") {
    const monday = addDays(today, 1 - isoDayOfWeek(today))
    return { from: monday, to: addDays(monday, 6) }
  }

  const { year, month } = monthOf(today)
  return {
    from: dateOf(year, month, 1),
    to: dateOf(year, month, lastDayOfMonth(year, month)),
  }
}
