import { isSameLocalCalendarDay } from '@/components/appointments/appointmentTime';
import type { TreatmentAppointment } from '@/types/treatment';

/**
 * For the selected calendar day: if it is today, pick the in-progress appointment,
 * otherwise the appointment whose start time is nearest to now; on other days pick
 * the first appointment of that day. Returns null when there are no appointments.
 */
export function pickAutoAppointment(
  appointments: TreatmentAppointment[],
  selectedDay: Date,
): string | null {
  if (appointments.length === 0) return null;

  const now = new Date();
  if (isSameLocalCalendarDay(selectedDay, now)) {
    const t = now.getTime();
    for (const a of appointments) {
      const s = new Date(a.startAt).getTime();
      const e = new Date(a.endAt).getTime();
      if (t >= s && t <= e) return a.id;
    }

    let nearest = appointments[0];
    let nearestDistance = Math.abs(new Date(nearest.startAt).getTime() - t);
    for (const appointment of appointments.slice(1)) {
      const distance = Math.abs(new Date(appointment.startAt).getTime() - t);
      if (distance < nearestDistance) {
        nearest = appointment;
        nearestDistance = distance;
      }
    }
    return nearest.id;
  }

  return appointments[0].id;
}

export function treatmentAppointmentHref(appointmentId?: string): string {
  if (!appointmentId) return '/treatment';
  return `/treatment?appointmentId=${encodeURIComponent(appointmentId)}`;
}
