/** Normalize API date (string or Date) to YYYY-MM-DD. */
function toYYYYMMDD(val) {
  if (val == null) return '';
  if (typeof val === 'string') return val.slice(0, 10);
  if (typeof val === 'object' && typeof val.getFullYear === 'function') {
    const y = val.getFullYear();
    const m = String(val.getMonth() + 1).padStart(2, '0');
    const d = String(val.getDate()).padStart(2, '0');
    return `${y}-${m}-${d}`;
  }
  return '';
}

/** True if the schedule has an occurrence on dateStr (YYYY-MM-DD). */
function scheduleOccursOnDate(schedule, dateStr) {
  const d = new Date(`${dateStr}T12:00:00`);
  const scheduledDateStr = toYYYYMMDD(schedule.scheduled_date);
  const scheduled = new Date(`${scheduledDateStr}T12:00:00`);
  if (Number.isNaN(d.getTime()) || Number.isNaN(scheduled.getTime())) return false;

  if (schedule.recurrence_type === 'once') {
    return scheduledDateStr === dateStr;
  }

  if (schedule.recurrence_type === 'weekly') {
    const dayOfWeek =
      schedule.recurrence_day_of_week != null
        ? Number(schedule.recurrence_day_of_week)
        : scheduled.getDay();
    return d.getDay() === dayOfWeek && d >= scheduled;
  }

  if (schedule.recurrence_type === 'monthly') {
    const dayOfMonth =
      schedule.recurrence_day_of_month != null
        ? Number(schedule.recurrence_day_of_month)
        : scheduled.getDate();
    const last = new Date(d.getFullYear(), d.getMonth() + 1, 0);
    return d.getDate() === dayOfMonth && dayOfMonth <= last.getDate() && d >= scheduled;
  }

  return false;
}

/**
 * If a reminder should be sent today for this schedule, returns the occurrence date (YYYY-MM-DD).
 * reminder_days_before: 0 = on the day of, 1+ = that many days before the occurrence.
 */
function getReminderOccurrenceDate(schedule, today = new Date()) {
  const reminderDays = Number(schedule.reminder_days_before ?? 0);
  const base = new Date(today);
  base.setHours(12, 0, 0, 0);
  const target = new Date(base);
  target.setDate(target.getDate() + (Number.isFinite(reminderDays) ? reminderDays : 0));
  const targetStr = toYYYYMMDD(target);
  return scheduleOccursOnDate(schedule, targetStr) ? targetStr : null;
}

module.exports = {
  toYYYYMMDD,
  scheduleOccursOnDate,
  getReminderOccurrenceDate,
};
