import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { CancellationBlockedError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseSalesInvoice,
  baseSalesOrder,
  confirmedSalesOrder,
  postedShipment,
} from "../testing/fixtures";
import { run } from "./cancelSalesOrder";

describe("cancelSalesOrder", () => {
  it("cancels a draft order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const cancelled = {
      ...baseSalesOrder,
      status: "CANCELLED",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    mock.enqueueResults([baseSalesOrder], [], [], [cancelled]);

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

    const value = expectOk(result);
    expect(value.salesOrder.status).toBe("CANCELLED");
  });

  it("cancels a confirmed order with no shipment or invoice evidence", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [confirmedSalesOrder],
      [],
      [],
      [{ ...confirmedSalesOrder, status: "CANCELLED" }],
    );

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

    expectOk(result);
  });

  it("throws when posted shipment evidence exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([confirmedSalesOrder], [postedShipment], []);

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

    expectErr(result, CancellationBlockedError);
  });

  it("throws when issued invoice evidence exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([confirmedSalesOrder], [], [{ ...baseSalesInvoice, status: "ISSUED" }]);

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

    expectErr(result, CancellationBlockedError);
  });
});
