/**
 * The saved-schedule → draft-row conversion for the learn & serve edit form.
 *
 * `LearnServeTimeSlotResource` and the draft `TimeSlot` disagree on three
 * fields, and the form used to hand one straight to the other. These pin the
 * disagreements rather than the happy path.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { learnServeSlotsToDrafts } from "@/features/opportunities/learnServeSlotDraft";
import type { LearnServeTimeSlotRecord } from "@/features/opportunities/opportunityRecord";

const slot = (over: Partial<LearnServeTimeSlotRecord> = {}): LearnServeTimeSlotRecord => ({
  id: 1,
  // The opportunity id arrives under `opportunity`, not `opportunity_id`.
  opportunity: 7,
  date: "2026-10-05",
  start_time: "09:00:00",
  end_time: "12:00:00",
  participants_needed: 5,
  created_at: null,
  updated_at: null,
  opportunity_start_date: null,
  opportunity_end_date: null,
  opportunity_start_time: null,
  opportunity_end_time: null,
  ...over,
});

describe("learnServeSlotsToDrafts", () => {
  test("null and undefined give an empty list, not a throw", () => {
    assert.deepEqual(learnServeSlotsToDrafts(null), []);
    assert.deepEqual(learnServeSlotsToDrafts(undefined), []);
  });

  test("every draft carries isSaved: false — the API never sends the flag", () => {
    // `handleConfirmAction` filters on `isSaved === true`, so an absent flag
    // and `false` behave alike; setting it makes the draft shape honest.
    const [draft] = learnServeSlotsToDrafts([slot()]);
    assert.equal(draft.isSaved, false);
  });

  test("a slot with no date is dropped rather than coerced to \"\"", () => {
    // An empty date renders a row the organiser cannot act on.
    assert.deepEqual(learnServeSlotsToDrafts([slot({ date: null })]), []);
  });

  test("null times and participant count fall back, they do not propagate", () => {
    const [draft] = learnServeSlotsToDrafts([
      slot({ start_time: null, end_time: null, participants_needed: null }),
    ]);
    assert.equal(draft.start_time, "");
    assert.equal(draft.end_time, "");
    assert.equal(draft.participants_needed, 0);
  });

  test("the id and date are carried through unchanged", () => {
    const [draft] = learnServeSlotsToDrafts([slot({ id: 42, date: "2026-11-01" })]);
    assert.equal(draft.id, 42);
    assert.equal(draft.date, "2026-11-01");
  });

  test("a mixed list keeps order and drops only the dateless rows", () => {
    const drafts = learnServeSlotsToDrafts([
      slot({ id: 1, date: "2026-10-01" }),
      slot({ id: 2, date: null }),
      slot({ id: 3, date: "2026-10-03" }),
    ]);
    assert.deepEqual(drafts.map((d) => d.id), [1, 3]);
  });
});
