import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseShipment, postedShipment, baseShipmentLine } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getShipment";

describe("getShipment", () => {
  it("returns shipment when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseShipment);
    spies.select.mockReturnValueOnce([baseShipmentLine]);

    const result = await run(db, { id: baseShipment.id });
    const { shipment } = expectOk<{ shipment: unknown }>(result as never);

    expect(shipment).not.toBeNull();
    expect(shipment).toMatchObject({ id: baseShipment.id });
  });

  it("returns posted shipment with lines", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(postedShipment);
    spies.select.mockReturnValueOnce([baseShipmentLine]);

    const result = await run(db, { id: postedShipment.id });
    const { shipment } = expectOk<{
      shipment: { status: string; lines: unknown[] };
    }>(result as never);

    expect(shipment.status).toBe("POSTED");
    expect(shipment.lines).toHaveLength(1);
  });

  it("returns null when shipment is not found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(db, { id: "non-existent-id" });
    const { shipment } = expectOk<{ shipment: null }>(result as never);

    expect(shipment).toBeNull();
  });
});
