import moment from "moment";
import { parseKuwaitInstant, reviewScheduleSlots, type ReviewSchedule } from "@/features/shared/clientReviewPolicy";

/** Latest client clarification: the final scheduled day's session start, without a lead hour. */
export function developmentScanOpensAt(item?: ReviewSchedule | null): moment.Moment | null {
  if (!item) return null;
  const slots = reviewScheduleSlots(item);
  const starts = slots.map(slot => {
    const day = slot.date?.slice(0, 10);
    const time = slot.start_time || item.start_time;
    return day && time ? parseKuwaitInstant(`${day}T${time}`) : null;
  }).filter((start): start is moment.Moment => start !== null);
  if (starts.length) {
    const lastDay = moment.max(starts).clone().startOf("day");
    return moment.min(starts.filter(start => start.isSame(lastDay, "day")));
  }
  const day = (item.end_date || item.start_date)?.slice(0, 10);
  if (day && item.start_time) return parseKuwaitInstant(`${day}T${item.start_time}`);
  // A one-day canonical-only response still supplies its precise first start.
  const start = parseKuwaitInstant(item.start_at);
  const end = parseKuwaitInstant(item.end_at);
  return start && end && start.isSame(end, "day") ? start : null;
}

/**
 * When the organizer's manual «حضر» is accepted (PDF p.19, A14): the server's
 * own `scan_opens_at` first, else the same instant derived from the schedule.
 * `updateAttendance()` answers 400 for `is_attended: true` before it, so the
 * start of the final day is not enough.
 */
export function developmentAttendanceOpensAt(item?: (ReviewSchedule & { scan_opens_at?: string | null }) | null): moment.Moment | null {
  return parseKuwaitInstant(item?.scan_opens_at) ?? developmentScanOpensAt(item);
}
