export interface Range {
  fromIso: string;
  toIso: string;
}

/**
 * Parses attendance query params into an [from, to) ISO range. Priority:
 *   1. explicit ?from=YYYY-MM-DD&to=YYYY-MM-DD (to is inclusive of that whole day)
 *   2. ?month=YYYY-MM — that whole calendar month
 *   3. default — the current calendar month
 */
export function parseRange(query: Record<string, unknown>): Range {
  const now = new Date();

  const from = typeof query.from === "string" && query.from ? new Date(query.from) : null;
  const toRaw = typeof query.to === "string" && query.to ? new Date(query.to) : null;

  if (from && toRaw) {
    const to = new Date(toRaw);
    to.setDate(to.getDate() + 1); // make "to" inclusive of that whole day
    return { fromIso: from.toISOString(), toIso: to.toISOString() };
  }

  const month = typeof query.month === "string" && /^\d{4}-\d{2}$/.test(query.month) ? query.month : null;
  const [year, monthIndex] = month
    ? [Number(month.slice(0, 4)), Number(month.slice(5, 7)) - 1]
    : [now.getFullYear(), now.getMonth()];

  const monthStart = new Date(year, monthIndex, 1);
  const monthEnd = new Date(year, monthIndex + 1, 1);

  return { fromIso: monthStart.toISOString(), toIso: monthEnd.toISOString() };
}
