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

describe("listInventoryCounts", () => {
  it("lists counts by status", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([basePlannedCount]);

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

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

  it("lists counts by type", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([basePlannedCount]);

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

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

  it("lists counts by warehouse", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([basePlannedCount]);

    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(basePlannedCount);
  });

  it("lists counts by date range", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([basePlannedCount]);

    const result = await run(db, {
      dateFrom: new Date("2024-01-01"),
      dateTo: new Date("2024-12-31"),
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

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

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

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

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

  it("orders by planned date descending", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([basePlannedCount, baseInProgressCount]);

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

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