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

describe("markChannelOrderException", () => {
  it("marks a pending channel order as exception with retry context", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannelOrder);
    spies.update.mockReturnValueOnce({
      ...baseChannelOrder,
      status: "EXCEPTION",
      retryContext: JSON.stringify({ attempt: 2 }),
      updatedAt: new Date(),
    });

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

    expectOk(result);
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({
        status: "EXCEPTION",
        retryContext: JSON.stringify({ attempt: 2 }),
      }),
    );
  });

  it("throws when channel order is not pending conversion", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseChannelOrder, status: "EXCEPTION" });

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

    expectErr(result, InvalidChannelOrderStatusError);
  });

  it("throws when exception context is empty", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannelOrder);

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

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