import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { SalesOrderIdRequiredError } from "../lib/errors.generated";
import { baseShipment, postedShipment, confirmedSalesOrder } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listShipmentsBySalesOrder";

describe("listShipmentsBySalesOrder", () => {
  it("lists shipments under a sales order", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseShipment]);

    const result = await run(db, { salesOrderId: confirmedSalesOrder.id });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("returns both draft and posted shipments when present", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseShipment, postedShipment]);

    const result = await run(db, { salesOrderId: confirmedSalesOrder.id });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(2);
  });

  it("throws when sales-order id is missing", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, { salesOrderId: "" });
    expectErr(result as never, SalesOrderIdRequiredError);
  });
});
