import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { StageNotFoundError } from "../lib/errors.generated";
import { baseItem, baseStage } from "../testing/fixtures";
import { run } from "./listPipelineItemsByStage";

describe("listPipelineItemsByStage", () => {
  it("returns items ordered by position ascending", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStage], [baseItem, { ...baseItem, id: "item-2", position: 2 }]);

    const result = await run(mock.db, { stageId: baseStage.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toHaveLength(2);
    }
  });

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

    const result = await run(mock.db, { stageId: baseStage.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items).toEqual([]);
    }
  });

  it("filters items to the specified stage only", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseStage], [baseItem]);

    const result = await run(mock.db, { stageId: baseStage.id });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.items.every((item) => item.stageId === baseStage.id)).toBe(true);
    }
  });

  it("returns error when stage does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { stageId: "missing-stage" });

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StageNotFoundError);
    }
  });
});
