import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { NoFilterProvidedError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { baseCostLayer } from "../testing/fixtures";
import { run } from "./listCostLayers";

describe("listCostLayers", () => {
  it("lists cost layers by item", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseCostLayer]);

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

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

  it("lists cost layers by valuation policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseCostLayer]);

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

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

  it("lists cost layers by both item and valuation policy", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseCostLayer]);

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

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

  it("returns results in oldest-first order", async () => {
    const { db, spies } = createMockDb<DB>();
    const olderLayer = {
      ...baseCostLayer,
      id: "cost-layer-old",
      createdAt: new Date("2024-01-01T00:00:00.000Z"),
    };
    const newerLayer = {
      ...baseCostLayer,
      id: "cost-layer-new",
      createdAt: new Date("2024-06-01T00:00:00.000Z"),
    };
    spies.select.mockReturnValueOnce([olderLayer, newerLayer]);

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

    expect(items).toHaveLength(2);
    expect(items[0].id).toBe("cost-layer-old");
    expect(items[1].id).toBe("cost-layer-new");
  });

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

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

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

  it("returns error when no filter is provided", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, {});
    expectErr(result as never, NoFilterProvidedError);
  });
});
