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

describe("placeSalesOrderOnCreditHold", () => {
  it("places a confirmed order on credit hold", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const held = {
      ...confirmedSalesOrder,
      status: "CREDIT_HOLD",
      holdReason: "Credit review",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    mock.enqueueResults([confirmedSalesOrder], [held]);

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

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

  it("preserves prior shipment and invoice progress when placing hold", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const order = { ...confirmedSalesOrder, status: "PARTIALLY_SHIPPED" as const };
    mock.enqueueResults([order], [{ ...order, status: "CREDIT_HOLD", holdReason: "Fraud check" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { salesOrderId: order.id, holdReason: "Fraud check" }, commandCtx),
    );

    expectOk(result);
    expect(mock.updates[0].updateValues()).toEqual(
      expect.objectContaining({ status: "CREDIT_HOLD", holdReason: "Fraud check" }),
    );
  });

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

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

    expectErr(result, InvalidOrderStatusError);
  });

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

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

    expectErr(result, HoldReasonRequiredError);
  });
});
