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

describe("releaseSalesOrderCreditHold", () => {
  it("releases a held order back to executable status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [heldSalesOrder],
      [{ quantity: 10, shippedQuantity: 4, invoicedQuantity: 0 }],
      [{ ...heldSalesOrder, status: "PARTIALLY_SHIPPED" as const, holdReason: null }],
    );

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

    expectOk(result);
  });

  it("preserves shipment and invoice progress when releasing hold", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [heldSalesOrder],
      [{ quantity: 10, shippedQuantity: 10, invoicedQuantity: 5 }],
      [{ ...heldSalesOrder, status: "PARTIALLY_INVOICED" as const, holdReason: null }],
    );

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

    expectOk(result);
  });

  it("throws when order is not on credit hold", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesOrder]);

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

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