import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidShipmentStatusError, OverShipmentNotAllowedError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseSalesOrderLine,
  baseShipment,
  baseShipmentLine,
  postedShipment,
} from "../testing/fixtures";
import { run } from "./postShipment";

describe("postShipment", () => {
  it("posts a shipment and updates order shipped progress", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const shipmentLine = { ...baseShipmentLine, shipmentId: baseShipment.id };
    const orderLine = { ...baseSalesOrderLine, salesOrderId: baseShipment.salesOrderId };
    mock.enqueueResults(
      [baseShipment],
      [shipmentLine],
      [orderLine],
      [{ ...orderLine, shippedQuantity: shipmentLine.quantity }],
      [{ ...orderLine, shippedQuantity: shipmentLine.quantity }],
      [{ id: baseShipment.salesOrderId, status: "CONFIRMED" }],
      [{ id: baseShipment.salesOrderId, status: "PARTIALLY_SHIPPED" }],
      [postedShipment],
    );

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

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

  it("throws when shipment quantity exceeds remaining order quantity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const shipmentLine = { ...baseShipmentLine, shipmentId: baseShipment.id };
    const orderLine = {
      ...baseSalesOrderLine,
      salesOrderId: baseShipment.salesOrderId,
      shippedQuantity: 9,
      quantity: 10,
    };
    mock.enqueueResults([baseShipment], [shipmentLine], [orderLine]);

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

    expectErr(result, OverShipmentNotAllowedError);
  });

  it("throws when posting a non-draft shipment", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([postedShipment]);

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

    expectErr(result, InvalidShipmentStatusError);
  });
});
