// Rule: the combined visitDate + visitTime can't be in the past unless the
// admin has the `canBackdateVisitor` flag (owner is always exempt).
//
// Semantics:
//   - No visitDate                 → unrestricted (no scheduled moment).
//   - visitDate today, no time     → unrestricted ("any time today").
//   - visitDate today + time       → the combined minute must be ≥ now.
//   - visitDate before today       → blocked regardless of time.
//
// The comparison floors `now` to the current minute so saving "right now"
// at e.g. 17:29:30 with visitTime=17:29 is accepted.
export function visitDateTimeIsInPast(
  visitDate: string | Date | null | undefined,
  visitTime: string | null | undefined,
): boolean {
  if (!visitDate) return false;
  const d = new Date(visitDate);
  if (!Number.isFinite(d.getTime())) return false;

  const now = new Date();
  const sameDay =
    d.getFullYear() === now.getFullYear() &&
    d.getMonth() === now.getMonth() &&
    d.getDate() === now.getDate();

  if (sameDay) {
    if (!visitTime) return false;
    const m = /^(\d{1,2}):(\d{2})/.exec(visitTime);
    if (!m) return false;
    const h = Number(m[1]);
    const min = Number(m[2]);
    if (!Number.isFinite(h) || !Number.isFinite(min)) return false;
    const moment = new Date(d.getFullYear(), d.getMonth(), d.getDate(), h, min, 0, 0);
    const nowFloor = new Date(now);
    nowFloor.setSeconds(0, 0);
    return moment.getTime() < nowFloor.getTime();
  }

  const dDateOnly = new Date(d.getFullYear(), d.getMonth(), d.getDate());
  const nowDateOnly = new Date(now.getFullYear(), now.getMonth(), now.getDate());
  return dDateOnly.getTime() < nowDateOnly.getTime();
}
