import { describe, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  CustomerNotActiveError,
  InvalidOrderStatusError,
  MissingFinalPriceError,
} from "../lib/errors.generated";
import {
  baseCustomer,
  basePaymentTerm,
  baseSalesOrderLine,
  inactiveCustomer,
  submittedSalesOrder,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./confirmSalesOrder";

describe("confirmSalesOrder", () => {
  it("confirms a submitted order and snapshots commercial context", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = {
      ...submittedSalesOrder,
      status: "CONFIRMED" as const,
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select
      .mockReturnValueOnce(submittedSalesOrder)
      .mockReturnValueOnce(baseCustomer)
      .mockReturnValueOnce([baseSalesOrderLine])
      .mockReturnValueOnce(basePaymentTerm);
    spies.update.mockReturnValueOnce(updated);

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

    expectOk(result);
  });

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

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

    expectErr(result, InvalidOrderStatusError);
  });

  it("throws when customer became inactive before confirmation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(submittedSalesOrder).mockReturnValueOnce(inactiveCustomer);

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

    expectErr(result, CustomerNotActiveError);
  });

  it("throws when a line lacks final pricing data", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(submittedSalesOrder)
      .mockReturnValueOnce(baseCustomer)
      .mockReturnValueOnce([{ ...baseSalesOrderLine, unitPrice: 0 }]);

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

    expectErr(result, MissingFinalPriceError);
  });
});
