import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { SalesOrderIdRequiredError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { baseShipment, postedShipment, confirmedSalesOrder } from "../testing/fixtures";
import { run } from "./listShipmentsBySalesOrder";

describe("listShipmentsBySalesOrder", () => {
  it("lists shipments under a sales order", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseShipment]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain(confirmedSalesOrder.id);
    expect(mock.selects[0].sql).toMatch(/"salesOrderId"/);
    expect(mock.selects[0].sql).toMatch(/order by .*"shipmentDate" desc/i);
  });

  it("returns both draft and posted shipments when present", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseShipment, postedShipment]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();

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