import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidChannelOrderStatusError } from "../lib/errors.generated";
import { baseChannelOrder } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./cancelChannelOrder";

describe("cancelChannelOrder", () => {
  it("cancels a pending channel order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannelOrder);
    spies.update.mockReturnValueOnce({
      ...baseChannelOrder,
      status: "CANCELLED_BY_CHANNEL",
      updatedAt: new Date(),
    });

    const result = await run(db, { channelOrderId: baseChannelOrder.id }, commandCtx);

    const value = expectOk(result);
    expect(value.channelOrder.status).toBe("CANCELLED_BY_CHANNEL");
  });

  it("cancels an exceptional channel order before replay", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const exceptional = { ...baseChannelOrder, status: "EXCEPTION" as const };
    spies.select.mockReturnValueOnce(exceptional);
    spies.update.mockReturnValueOnce({ ...exceptional, status: "CANCELLED_BY_CHANNEL" });

    const result = await run(db, { channelOrderId: exceptional.id }, commandCtx);

    expectOk(result);
  });

  it("prevents stale conversion after cancellation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({
      ...baseChannelOrder,
      status: "CANCELLED_BY_CHANNEL",
    });

    const result = await run(db, { channelOrderId: baseChannelOrder.id }, commandCtx);

    expectErr(result, InvalidChannelOrderStatusError);
  });
});
