/**
 * Reminder date maths shared by the call journal and the visit form.
 *
 * Default is CRM `Constants::getBusnissDays` parity: Saturday and Sunday do not count.
 * The account can opt out with the CRM setting « Autoriser les rappels le week-end »,
 * which arrives on the mobile profile as `reminderIncludeWeekend`.
 */

function atTen(d: Date): Date {
  d.setHours(10, 0, 0, 0);
  return d;
}

/** +N calendar days at 10:00. */
export function atTenInCalendarDays(days: number): Date {
  const d = new Date();
  d.setDate(d.getDate() + Math.max(1, days));
  return atTen(d);
}

/** +N weekdays at 10:00 (0 = Sunday, 6 = Saturday are skipped). */
export function atTenInBusinessDays(businessDays: number): Date {
  const d = new Date();
  let left = Math.max(1, businessDays);
  while (left > 0) {
    d.setDate(d.getDate() + 1);
    const day = d.getDay();
    if (day !== 0 && day !== 6) left -= 1;
  }
  return atTen(d);
}

/** +N days at 10:00, weekends counted only when the account allows it. */
export function atTenInReminderDays(days: number, includeWeekend?: boolean): Date {
  return includeWeekend ? atTenInCalendarDays(days) : atTenInBusinessDays(days);
}

function sameCalendarDay(a: Date, b: Date): boolean {
  return (
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
  );
}

/** True when the reminder was pushed past a weekend — used for the inline hint. */
export function reminderSkippedWeekend(days: number, reminderAt: Date): boolean {
  return !sameCalendarDay(atTenInCalendarDays(days), reminderAt);
}
