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

describe("listPipelineStageTransitionsByItem", () => {
  it("returns transitions ordered by createdAt ascending", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [basePipelineStageTransition]);

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

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

  it("returns empty list when item has no transitions", 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.transitions).toEqual([]);
    }
  });

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

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(
        result.value.transitions.every((transition) => transition.itemId === baseItem.id),
      ).toBe(true);
    }
  });

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