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

describe("listExpiringLots", () => {
  it("returns lots expiring within threshold", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseActiveLot]);

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

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

  it("sorts by expiration date ascending", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseActiveLot]);

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

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

  it("excludes fully consumed lots", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([]);

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

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

  it("filters by item when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseActiveLot]);

    const result = await run(db, { daysUntilExpiry: 365, itemId: "item-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

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

  it("filters by warehouse when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([{ id: "location-1" }]);
    spies.select.mockReturnValueOnce([{ lotId: "lot-1" }]);
    spies.select.mockReturnValueOnce([baseActiveLot]);

    const result = await run(db, { daysUntilExpiry: 365, warehouseId: "warehouse-1" });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

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

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

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

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