import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { baseActiveLot, baseLotStockLevel } from "../testing/fixtures";
import { run } from "./getLot";

describe("getLot", () => {
  it("returns lot when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot], [baseLotStockLevel]);

    const result = await run(mock.db, { id: "lot-1" });
    const { lot } = expectOk<{ lot: unknown }>(result as never);

    expect(lot).not.toBeNull();
    expect(lot).toMatchObject({ id: "lot-1" });
  });

  it("returns lot when found by lotNumber and itemId", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot], [baseLotStockLevel]);

    const result = await run(mock.db, { lotNumber: "LOT-001", itemId: "item-1" });
    const { lot } = expectOk<{ lot: unknown }>(result as never);

    expect(lot).not.toBeNull();
    expect(lot).toMatchObject({ id: "lot-1", lotNumber: "LOT-001" });
  });

  it("returns null when not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "non-existent" });
    const { lot, lotStockLevels } = expectOk<{
      lot: null;
      lotStockLevels: unknown[];
    }>(result as never);

    expect(lot).toBeNull();
    expect(lotStockLevels).toEqual([]);
  });

  it("includes lot stock levels across locations", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot], [baseLotStockLevel]);

    const result = await run(mock.db, { id: "lot-1" });
    const { lotStockLevels } = expectOk<{ lotStockLevels: unknown[] }>(result as never);

    expect(lotStockLevels).toHaveLength(1);
    expect(lotStockLevels[0]).toMatchObject({
      lotId: "lot-1",
      storageLocationId: "location-1",
      onHand: "50",
    });
  });
});
