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

describe("listStorageLocations", () => {
  it("lists storage locations by warehouse", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseZone, baseBin]);

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

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

  it("lists storage locations by status", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseZone]);

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

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

  it("lists top-level zones when parentId is null", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseZone]);

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

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

  it("lists bins under a specific zone", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseBin]);

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

    expect(items[0].locationType).toBe("bin");
  });

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

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

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

  it("orders by name ascending", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseBin, baseZone]);

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

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