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

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

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

    expect(storageLocation).not.toBeNull();
    expect(storageLocation).toMatchObject({ id: baseStorageLocation.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(baseStorageLocation);
    spies.select.mockReturnValueOnce([baseStockLevel]);

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

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