import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidChannelOrderStatusError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { baseChannelOrder } from "../testing/fixtures";
import { run } from "./cancelChannelOrder";

describe("cancelChannelOrder", () => {
  it("cancels a pending channel order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseChannelOrder],
      [
        {
          ...baseChannelOrder,
          status: "CANCELLED_BY_CHANNEL",
          updatedAt: new Date(),
        },
      ],
    );

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const exceptional = { ...baseChannelOrder, status: "EXCEPTION" as const };
    mock.enqueueResults([exceptional], [{ ...exceptional, status: "CANCELLED_BY_CHANNEL" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { channelOrderId: exceptional.id }, commandCtx),
    );

    expectOk(result);
  });

  it("prevents stale conversion after cancellation", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([
      {
        ...baseChannelOrder,
        status: "CANCELLED_BY_CHANNEL",
      },
    ]);

    const result = await mock.withTx((trx) =>
      run(trx, { channelOrderId: baseChannelOrder.id }, commandCtx),
    );

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