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

describe("releaseSalesOrderCreditHold", () => {
  it("releases a held order back to executable status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(heldSalesOrder)
      .mockReturnValueOnce([{ quantity: 10, shippedQuantity: 4, invoicedQuantity: 0 }]);
    spies.update.mockReturnValueOnce({
      ...heldSalesOrder,
      status: "PARTIALLY_SHIPPED" as const,
      holdReason: null,
    });

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

    expectOk(result);
  });

  it("preserves shipment and invoice progress when releasing hold", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(heldSalesOrder)
      .mockReturnValueOnce([{ quantity: 10, shippedQuantity: 10, invoicedQuantity: 5 }]);
    spies.update.mockReturnValueOnce({
      ...heldSalesOrder,
      status: "PARTIALLY_INVOICED" as const,
      holdReason: null,
    });

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

    expectOk(result);
  });

  it("throws when order is not on credit hold", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseSalesOrder);

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

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