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

describe("getWarehouse", () => {
  it("returns warehouse when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseActiveWarehouse);
    spies.select.mockReturnValueOnce([baseZone]);

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

    expect(warehouse).not.toBeNull();
    expect(warehouse).toMatchObject({ id: baseActiveWarehouse.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 { warehouse, storageLocations } = expectOk<{
      warehouse: unknown;
      storageLocations: unknown[];
    }>(result as never);

    expect(warehouse).toBeNull();
    expect(storageLocations).toEqual([]);
  });

  it("includes associated storage locations", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseActiveWarehouse);
    spies.select.mockReturnValueOnce([baseZone, baseBin]);

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

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

  it("includes storage condition and capacity", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInactiveWarehouse);
    spies.select.mockReturnValueOnce([]);

    const result = await run(db, { id: baseInactiveWarehouse.id });
    const { warehouse } = expectOk<{
      warehouse: { storageCondition: string; capacity: number };
    }>(result as never);

    expect(warehouse.storageCondition).toBe("cold");
    expect(warehouse.capacity).toBe(5000);
  });
});
