import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import {
  baseInProgressCount,
  basePendingCountLine,
  baseApprovedCountLine,
} from "../testing/fixtures";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { CountNotFoundError } from "../lib/errors.generated";
import { run } from "./getInventoryCount";

describe("getInventoryCount", () => {
  it("returns count with lines when found", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInProgressCount);
    spies.select.mockReturnValueOnce([basePendingCountLine, baseApprovedCountLine]);

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

    expect(inventoryCount).toMatchObject({ id: baseInProgressCount.id });
    expect(countLines).toHaveLength(2);
  });

  it("includes variance for each line", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInProgressCount);
    spies.select.mockReturnValueOnce([basePendingCountLine]);

    const result = await run(db, { id: baseInProgressCount.id });
    const { countLines } = expectOk<{
      inventoryCount: unknown;
      countLines: { variance: number }[];
    }>(result as never);

    expect(countLines[0].variance).toBe(-2);
  });

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

    const result = await run(db, { id: "nonexistent-id" });
    expectErr(result as never, CountNotFoundError);
  });

  it("includes line status (pending/approved/rejected/recount)", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseInProgressCount);
    spies.select.mockReturnValueOnce([basePendingCountLine, baseApprovedCountLine]);

    const result = await run(db, { id: baseInProgressCount.id });
    const { countLines } = expectOk<{
      inventoryCount: unknown;
      countLines: { status: string }[];
    }>(result as never);

    expect(countLines[0].status).toBe("PENDING");
    expect(countLines[1].status).toBe("APPROVED");
  });
});
