/**
 * The consultation time-slot create payload.
 *
 * `LearnServeTimeSlotController::store()` validates
 * `'opportunity_id' => ['required', 'integer', 'exists:learn_serve_opportunities,id']`
 * and then reads `$data['opportunity_id']`. The frontend was sending
 * `opportunity`, with nothing on the backend remapping it — so **every create
 * was rejected with 422** while the edit path kept working, because
 * `update()` validates with `sometimes` and takes the opportunity from the
 * query string.
 *
 * These tests drive the real submit handler with stub mutations and assert on
 * the body it builds, so the key cannot drift back.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";

import { useTimeSlotSubmit } from "@/features/opportunities/components/useTimeSlotSubmit";
import type { TimeSlotPayload } from "@/features/opportunities/components/useTimeSlotSubmit";

type Captured = { created: TimeSlotPayload[]; updated: unknown[] };

const build = (over: { isEditing?: boolean; editTimeSlot?: unknown } = {}) => {
  const captured: Captured = { created: [], updated: [] };
  const submit = useTimeSlotSubmit({
    opportunityId: "42",
    isEditing: over.isEditing ?? false,
    editTimeSlot: (over.editTimeSlot ?? null) as never,
    t: (key: string) => key,
    selectedLanguage: "en",
    setOpenForm: () => {},
    refetch: () => {},
    createTimeSlotMutation: {
      mutateAsync: async (payload: TimeSlotPayload) => {
        captured.created.push(payload);
        return {};
      },
    },
    updateTimeSlotMutation: {
      mutateAsync: async (payload) => {
        captured.updated.push(payload);
        return {};
      },
    },
  });
  return { submit, captured };
};

const values = {
  date: "2027-05-10",
  startTime: "09:00",
  endTime: "10:30",
  needed: "12",
} as never;

const helpers = { resetForm: () => {} } as never;

describe("creating a time slot", () => {
  test("sends opportunity_id — the key the controller validates", async () => {
    const { submit, captured } = build();
    await submit(values, helpers);
    assert.equal(captured.created.length, 1);
    const body = captured.created[0];
    assert.ok(
      "opportunity_id" in body,
      "the controller requires opportunity_id and reads it directly"
    );
    assert.equal(body.opportunity_id, 42);
  });

  test("does NOT send the old `opportunity` key", async () => {
    const { submit, captured } = build();
    await submit(values, helpers);
    assert.ok(
      !("opportunity" in captured.created[0]),
      "`opportunity` is not in the validation list and was the cause of the 422"
    );
  });

  test("opportunity_id is a number, matching the `integer` rule", async () => {
    const { submit, captured } = build();
    await submit(values, helpers);
    assert.equal(typeof captured.created[0].opportunity_id, "number");
  });

  test("the rest of the body matches the validated keys exactly", async () => {
    const { submit, captured } = build();
    await submit(values, helpers);
    assert.deepEqual(Object.keys(captured.created[0]).sort(), [
      "date",
      "end_time",
      "opportunity_id",
      "participants_needed",
      "start_time",
    ]);
  });

  test("times are sent with seconds and the date as yyyy-MM-dd", async () => {
    const { submit, captured } = build();
    await submit(values, helpers);
    const body = captured.created[0];
    assert.equal(body.start_time, "09:00:00");
    assert.equal(body.end_time, "10:30:00");
    assert.equal(body.date, "2027-05-10");
    assert.equal(body.participants_needed, 12);
  });

  test("an unparseable date aborts before any request", async () => {
    const { submit, captured } = build();
    await submit({ ...(values as object), date: "" } as never, helpers);
    assert.equal(captured.created.length, 0);
  });
});

describe("editing a time slot", () => {
  test("goes to the update call, with the opportunity in the query argument", async () => {
    const { submit, captured } = build({
      isEditing: true,
      editTimeSlot: { id: 7 },
    });
    await submit(values, helpers);
    assert.equal(captured.created.length, 0);
    assert.equal(captured.updated.length, 1);
    assert.deepEqual(
      Object.keys(captured.updated[0] as object).sort(),
      ["data", "id", "opportunity_id"]
    );
  });

  test("a missing slot id aborts rather than updating the wrong row", async () => {
    const { submit, captured } = build({
      isEditing: true,
      editTimeSlot: { id: undefined },
    });
    await submit(values, helpers);
    assert.equal(captured.updated.length, 0);
  });
});
