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

describe("listPipelineLabelsByItem", () => {
  it("returns labels attached to the item ordered by name ascending", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const second = { ...baseLabel, id: "label-2", name: "frontend" };
    mock.enqueueResults([baseItem], [second, baseLabel]);

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

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

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

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

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

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

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

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