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

describe("markChannelOrderException", () => {
  it("marks a pending channel order as exception with retry context", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseChannelOrder],
      [
        {
          ...baseChannelOrder,
          status: "EXCEPTION",
          retryContext: JSON.stringify({ attempt: 2 }),
          updatedAt: new Date(),
        },
      ],
    );

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

    expectOk(result);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({
        status: "EXCEPTION",
        retryContext: JSON.stringify({ attempt: 2 }),
      }),
    );
  });

  it("throws when channel order is not pending conversion", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseChannelOrder, status: "EXCEPTION" }]);

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

    expectErr(result, InvalidChannelOrderStatusError);
  });

  it("throws when exception context is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannelOrder]);

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

    expectErr(result, ExceptionContextRequiredError);
  });
});
