import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidShipmentLineError, OrderNotShippableError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseShipment,
  baseShipmentLineInput,
  confirmedSalesOrder,
  baseSalesOrderLine,
} from "../testing/fixtures";
import { run } from "./createShipment";

describe("createShipment", () => {
  it("creates a draft shipment against a confirmed order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const orderLine = { ...baseSalesOrderLine, salesOrderId: confirmedSalesOrder.id };
    mock.enqueueResults([confirmedSalesOrder], [orderLine], [baseShipment]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: {
            companyId: confirmedSalesOrder.companyId,
            salesOrderId: confirmedSalesOrder.id,
          },
          lines: [baseShipmentLineInput],
        },
        commandCtx,
      ),
    );

    const value = expectOk(result);
    expect(value.shipment.status).toBe("DRAFT");
  });

  it("throws when order has no open shippable quantity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const orderLine = {
      ...baseSalesOrderLine,
      salesOrderId: confirmedSalesOrder.id,
      shippedQuantity: baseSalesOrderLine.quantity,
    };
    mock.enqueueResults([confirmedSalesOrder], [orderLine]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: {
            companyId: confirmedSalesOrder.companyId,
            salesOrderId: confirmedSalesOrder.id,
          },
          lines: [baseShipmentLineInput],
        },
        commandCtx,
      ),
    );

    expectErr(result, OrderNotShippableError);
  });

  it("throws when shipment line quantity is not positive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const orderLine = { ...baseSalesOrderLine, salesOrderId: confirmedSalesOrder.id };
    mock.enqueueResults([confirmedSalesOrder], [orderLine]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: {
            companyId: confirmedSalesOrder.companyId,
            salesOrderId: confirmedSalesOrder.id,
          },
          lines: [{ ...baseShipmentLineInput, quantity: 0 }],
        },
        commandCtx,
      ),
    );

    expectErr(result, InvalidShipmentLineError);
  });
});
