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

describe("submitSalesOrder", () => {
  it("submits a complete draft order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const submitted = {
      ...baseSalesOrder,
      status: "SUBMITTED",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    mock.enqueueResults([baseSalesOrder], [baseSalesOrderLine], [submitted]);

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

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

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

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

    expectErr(result, InvalidOrderStatusError);
  });

  it("throws when the order has no lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSalesOrder], []);

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

    expectErr(result, EmptyOrderNotAllowedError);
  });

  it("throws when shipping address is missing for physical fulfillment lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [{ ...baseSalesOrder, shippingAddressSnapshot: null }],
      [baseSalesOrderLine],
    );

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

    expectErr(result, ShippingAddressRequiredError);
  });
});
