import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { baseActiveLot } from "../testing/fixtures";
import { run } from "./listExpiringLots";

describe("listExpiringLots", () => {
  it("returns lots expiring within threshold", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].sql).toMatch(/order by .*"expirationDate" asc/i);
  });

  it("excludes fully consumed lots", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveLot]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("item-1");
    expect(mock.selects[0].sql).toMatch(/"Lot"."itemId"/);
  });

  it("filters by warehouse when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ id: "location-1" }], [{ lotId: "lot-1" }], [baseActiveLot]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("site-1");
  });

  it("returns empty list when no expiring lots", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

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

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