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

describe("listPipelineStagesByPipeline", () => {
  it("returns stages ordered by position ascending", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePipeline], [baseStage, inProgressStage]);

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

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

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

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

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

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

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stages.every((stage) => stage.pipelineId === basePipeline.id)).toBe(true);
    }
  });

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

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

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