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

describe("closeSalesOrder", () => {
  it("closes an order with no remaining open balance", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [confirmedSalesOrder],
      [{ quantity: 10, shippedQuantity: 10, invoicedQuantity: 10 }],
      [{ ...confirmedSalesOrder, status: "CLOSED" as const }],
    );

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

    expectOk(result);
  });

  it("throws when remaining quantity is still open", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [confirmedSalesOrder],
      [{ quantity: 10, shippedQuantity: 10, invoicedQuantity: 5 }],
    );

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

    expectErr(result, OrderNotClosableError);
  });

  it("throws when order status does not allow closure", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...confirmedSalesOrder, status: "DRAFT" }]);

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

    expectErr(result, InvalidOrderStatusError);
  });
});
