import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { HoldReasonRequiredError, InvalidOrderStatusError } from "../lib/errors.generated";
import { confirmedSalesOrder } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./placeSalesOrderOnCreditHold";

describe("placeSalesOrderOnCreditHold", () => {
  it("places a confirmed order on credit hold", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const held = {
      ...confirmedSalesOrder,
      status: "CREDIT_HOLD",
      holdReason: "Credit review",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select.mockReturnValueOnce(confirmedSalesOrder);
    spies.update.mockReturnValueOnce(held);

    const result = await run(
      db,
      { 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 { db, spies } = createMockDb<Transaction>();
    const order = { ...confirmedSalesOrder, status: "PARTIALLY_SHIPPED" as const };
    spies.select.mockReturnValueOnce(order);
    spies.update.mockReturnValueOnce({
      ...order,
      status: "CREDIT_HOLD",
      holdReason: "Fraud check",
    });

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

    expectOk(result);
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "CREDIT_HOLD", holdReason: "Fraud check" }),
    );
  });

  it("throws when order is not in an executable status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...confirmedSalesOrder, status: "DRAFT" });

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

    expectErr(result, InvalidOrderStatusError);
  });

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

    const result = await run(
      db,
      { salesOrderId: confirmedSalesOrder.id, holdReason: "   " },
      commandCtx,
    );

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