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

describe("getStorageLocation", () => {
  it("returns storage location when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseZone);
    spies.select.mockReturnValueOnce([baseStockLevel]);

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

    expect(storageLocation).not.toBeNull();
    expect(storageLocation).toMatchObject({ id: baseZone.id });
  });

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

    const result = await run(db, { id: "nonexistent-id" });
    const { storageLocation } = expectOk<{ storageLocation: unknown }>(result as never);

    expect(storageLocation).toBeNull();
  });

  it("includes associated stock levels", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseZone);
    spies.select.mockReturnValueOnce([baseStockLevel]);

    const result = await run(db, { id: baseZone.id });
    const { stockLevels } = expectOk<{ stockLevels: unknown[] }>(result as never);

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

  it("includes parent zone reference for bins", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseBin);
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { id: baseBin.id });
    const { storageLocation } = expectOk<{
      storageLocation: { parentId: string };
    }>(result as never);

    expect(storageLocation.parentId).toBe("location-1");
  });
});
