import type { TimeSlot } from "@/features/shared/types/timeSlot";
import type { LearnServeTimeSlotRecord } from "./opportunityRecord";

/**
 * Turns the saved schedule an opportunity comes back with into the draft rows
 * the time-slot modal edits.
 *
 * These are two different shapes and the edit form was handing one straight to
 * the other:
 *
 * - **`isSaved` does not exist on the API row.** It is a client-only flag, and
 *   `useTimeSlotModals.handleConfirmAction` reads it as `slot.isSaved === true`
 *   to decide which rows survive a discard. Seeding without it left every row
 *   at `undefined`, which happens to behave the same as `false` for that
 *   comparison — so this is a correctness-preserving change, not a bug fix.
 *   It is made explicit because the next reader of `isSaved: boolean` has no
 *   way to know the field is sometimes simply absent.
 * - **`date` and `participants_needed` are nullable on the API row** and are
 *   required on the draft. `LearnServeTimeSlotResource` emits
 *   `optional($this->date)?->format('Y-m-d')`, so a slot with no date arrives
 *   as null. A null date is dropped rather than coerced: `""` would render an
 *   empty row the organiser cannot act on, and `participants_needed` falls
 *   back to 0, which is what the modal's own empty state submits.
 */
export function learnServeSlotsToDrafts(
  saved: readonly LearnServeTimeSlotRecord[] | null | undefined
): TimeSlot[] {
  const drafts: TimeSlot[] = [];
  for (const slot of saved ?? []) {
    if (!slot.date) continue;
    drafts.push({
      id: slot.id,
      date: slot.date,
      start_time: slot.start_time ?? "",
      end_time: slot.end_time ?? "",
      participants_needed: slot.participants_needed ?? 0,
      isSaved: false,
    });
  }
  return drafts;
}
