/**
 * Regression tests for the order a volunteering save happens in.
 *
 * These are the assertions the payload tests cannot make: `buildVolunteerPayload`
 * says what one request contains, this says which requests are sent, in what
 * order, and what happens when one of them fails. The ordering is a real
 * contract — sponsors are synced against a record that must already exist, and
 * removed images are deleted only after the record has accepted the new
 * keep-set — and nothing about getting it backwards fails to compile.
 */
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import {
  runVolunteerCreate,
  runVolunteerUpdate,
  type VolunteerCreateSteps,
  type VolunteerUpdateSteps,
} from "@/features/opportunities/components/volunteerSubmitSteps";

/** Records every step the sequence takes, in order. */
function updateSteps(over: Partial<VolunteerUpdateSteps> = {}) {
  const calls: string[] = [];
  const steps: VolunteerUpdateSteps = {
    save: async () => {
      calls.push("save");
      return { interestsDropped: false };
    },
    deleteImages: async (ids) => {
      calls.push(`deleteImages(${ids.join(",")})`);
    },
    syncSponsors: async (ids) => {
      calls.push(`syncSponsors(${ids.join(",")})`);
    },
    resubmit: async () => {
      calls.push("resubmit");
    },
    ...over,
  };
  return { calls, steps };
}

const runUpdate = (
  steps: VolunteerUpdateSteps,
  over: {
    removedImageIds?: number[];
    sponsorIds?: string[];
    isRejected?: boolean;
  } = {}
) =>
  runVolunteerUpdate({
    formData: new FormData(),
    removedImageIds: [],
    sponsorIds: [],
    isRejected: false,
    steps,
    ...over,
  });

describe("runVolunteerUpdate — the order of the requests", () => {
  test("saves, then deletes removed images, then syncs sponsors", async () => {
    const { calls, steps } = updateSteps();
    await runUpdate(steps, { removedImageIds: [4, 5], sponsorIds: ["9"] });
    assert.deepEqual(calls, ["save", "deleteImages(4,5)", "syncSponsors(9)"]);
  });

  test("skips the image deletion when nothing was removed", async () => {
    const { calls, steps } = updateSteps();
    await runUpdate(steps, { removedImageIds: [] });
    assert.deepEqual(calls, ["save", "syncSponsors()"]);
  });

  test("syncs sponsors even with an empty list — that is how one is removed", async () => {
    const { calls, steps } = updateSteps();
    await runUpdate(steps, { sponsorIds: [] });
    assert.ok(calls.includes("syncSponsors()"));
  });

  test("does NOT delete images when the save fails", async () => {
    // Deleting first would destroy images the record still references.
    const { calls, steps } = updateSteps({
      save: async () => {
        throw new Error("422");
      },
    });
    await assert.rejects(
      () => runUpdate(steps, { removedImageIds: [4] }),
      /422/
    );
    assert.deepEqual(calls, []);
  });

  test("a failed image deletion stops the sequence and throws", async () => {
    const { calls, steps } = updateSteps({
      deleteImages: async () => {
        throw new Error("deletion refused");
      },
    });
    await assert.rejects(
      () => runUpdate(steps, { removedImageIds: [4] }),
      /deletion refused/
    );
    // The sponsor sync must not have run — the organizer has to see this.
    assert.deepEqual(calls, ["save"]);
  });

  test("a failed sponsor sync throws", async () => {
    const { steps } = updateSteps({
      syncSponsors: async () => {
        throw new Error("sponsor route 500");
      },
    });
    await assert.rejects(() => runUpdate(steps), /sponsor route 500/);
  });
});

describe("runVolunteerUpdate — requeueing a rejected record", () => {
  test("an approved record is not resubmitted", async () => {
    const { calls, steps } = updateSteps();
    const outcome = await runUpdate(steps, { isRejected: false });
    assert.ok(!calls.includes("resubmit"));
    assert.deepEqual(outcome, {
      interestsDropped: false,
      resubmitted: false,
      resubmitFailed: false,
    });
  });

  test("a rejected record is resubmitted last, after the sponsors", async () => {
    const { calls, steps } = updateSteps();
    const outcome = await runUpdate(steps, { isRejected: true });
    assert.deepEqual(calls, ["save", "syncSponsors()", "resubmit"]);
    assert.equal(outcome.resubmitted, true);
    assert.equal(outcome.resubmitFailed, false);
  });

  test("a failed resubmit is REPORTED, not thrown — the edit was saved", async () => {
    // Throwing here would tell the organizer the whole update failed, when in
    // fact their changes are stored and only the requeue did not happen.
    const { steps } = updateSteps({
      resubmit: async () => {
        throw new Error("already in queue");
      },
    });
    const outcome = await runUpdate(steps, { isRejected: true });
    assert.deepEqual(outcome, {
      interestsDropped: false,
      resubmitted: false,
      resubmitFailed: true,
    });
  });

  test("dropped interest ids are carried through to the caller", async () => {
    const { steps } = updateSteps({
      save: async () => ({ interestsDropped: true }),
    });
    const outcome = await runUpdate(steps);
    assert.equal(outcome.interestsDropped, true);
  });
});

describe("runVolunteerCreate", () => {
  const createSteps = (over: Partial<VolunteerCreateSteps> = {}) => {
    const calls: string[] = [];
    const steps: VolunteerCreateSteps = {
      create: async () => {
        calls.push("create");
        return { interestsDropped: false, opportunityId: "77" };
      },
      syncSponsors: async (opportunityId, ids) => {
        calls.push(`syncSponsors(${opportunityId}, ${ids.join(",")})`);
      },
      ...over,
    };
    return { calls, steps };
  };

  const runCreate = (steps: VolunteerCreateSteps, sponsorIds: string[] = []) =>
    runVolunteerCreate({ formData: new FormData(), sponsorIds, steps });

  test("creates, then syncs sponsors against the id it got back", async () => {
    const { calls, steps } = createSteps();
    const outcome = await runCreate(steps, ["3", "8"]);
    assert.deepEqual(calls, ["create", "syncSponsors(77, 3,8)"]);
    assert.equal(outcome.opportunityId, "77");
  });

  test("skips the sponsor sync when the response carried no id", async () => {
    // A blank id would 404 against every sponsor route.
    const { calls, steps } = createSteps({
      create: async () => ({ interestsDropped: false, opportunityId: null }),
    });
    const outcome = await runCreate(steps, ["3"]);
    assert.deepEqual(calls, []);
    assert.equal(outcome.opportunityId, null);
  });

  test("a failed create never reaches the sponsor sync", async () => {
    const { calls, steps } = createSteps({
      create: async () => {
        throw new Error("422");
      },
    });
    await assert.rejects(() => runCreate(steps), /422/);
    assert.deepEqual(calls, []);
  });

  test("a failed sponsor sync is returned with the id, since the opportunity exists (S-VOL-2)", async () => {
    const { steps } = createSteps({
      syncSponsors: async () => {
        throw new Error("sponsor route 500");
      },
    });
    const outcome = await runCreate(steps, ["3"]);
    assert.ok(outcome.opportunityId != null);
    assert.match(String((outcome.sponsorError as Error).message), /sponsor route 500/);
  });

  test("dropped interest ids are carried through", async () => {
    const { steps } = createSteps({
      create: async () => ({ interestsDropped: true, opportunityId: "77" }),
    });
    const outcome = await runCreate(steps);
    assert.equal(outcome.interestsDropped, true);
  });
});
