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 { baseLabel, basePipeline } from "../testing/fixtures";
import { run } from "./listPipelineLabelsByPipeline";

describe("listPipelineLabelsByPipeline", () => {
  it("returns labels ordered by name ascending", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const second = { ...baseLabel, id: "label-2", name: "blocked" };
    mock.enqueueResults([basePipeline], [second, baseLabel]);

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

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

  it("returns empty list for a pipeline with no labels", 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.labels).toEqual([]);
    }
  });

  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);
    }
  });
});
