import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidShipmentLineError, OrderNotShippableError } from "../lib/errors.generated";
import {
  baseShipment,
  baseShipmentLine,
  baseShipmentLineInput,
  confirmedSalesOrder,
  baseSalesOrderLine,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./createShipment";

describe("createShipment", () => {
  it("creates a draft shipment against a confirmed order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderLine = { ...baseSalesOrderLine, salesOrderId: confirmedSalesOrder.id };
    spies.select.mockReturnValueOnce(confirmedSalesOrder).mockReturnValueOnce(orderLine);
    spies.insert.mockReturnValueOnce(baseShipment).mockReturnValueOnce(baseShipmentLine);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    const orderLine = {
      ...baseSalesOrderLine,
      salesOrderId: confirmedSalesOrder.id,
      shippedQuantity: baseSalesOrderLine.quantity,
    };
    spies.select.mockReturnValueOnce(confirmedSalesOrder).mockReturnValueOnce(orderLine);

    const result = await run(
      db,
      {
        companyId: confirmedSalesOrder.companyId,
        salesOrderId: confirmedSalesOrder.id,
        lines: [baseShipmentLineInput],
      },
      commandCtx,
    );

    expectErr(result, OrderNotShippableError);
  });

  it("throws when shipment line quantity is not positive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const orderLine = { ...baseSalesOrderLine, salesOrderId: confirmedSalesOrder.id };
    spies.select.mockReturnValueOnce(confirmedSalesOrder).mockReturnValueOnce(orderLine);

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

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