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

describe("listStockLevels", () => {
  it("lists stock levels by item across all locations", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseStockLevel]);

    const result = await run(db, { itemId: "item-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toEqual(baseStockLevel);
  });

  it("lists stock levels by storage location", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseStockLevel]);

    const result = await run(db, { storageLocationId: "location-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toEqual(baseStockLevel);
  });

  it("lists stock levels by warehouse (aggregates all locations)", async () => {
    const { db, spies } = createMockDb<DB>();
    // First select: StorageLocation ids by warehouseId
    spies.select.mockReturnValueOnce([{ id: "location-1" }]);
    // Second select: StockLevel where storageLocationId in those ids
    spies.select.mockReturnValueOnce([baseStockLevel]);

    const result = await run(db, { warehouseId: "warehouse-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toEqual(baseStockLevel);
  });

  it("returns empty list when no matches", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { itemId: "non-existent" });
    const { items, hasNextPage } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(
      result as never,
    );

    expect(items).toHaveLength(0);
    expect(hasNextPage).toBe(false);
  });

  it("includes computed available quantity", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseStockLevel]);

    const result = await run(db, { itemId: "item-1" });
    const { items } = expectOk<{
      items: { onHand: number; reserved: number; incoming: number; blocked: number }[];
      hasNextPage: boolean;
    }>(result as never);

    expect(items[0].onHand).toBe(100);
    expect(items[0].reserved).toBe(10);
    expect(items[0].incoming).toBe(20);
    expect(items[0].blocked).toBe(5);
  });
});
