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

describe("listPipelineItemCommentsByItem", () => {
  it("returns comments ordered by createdAt ascending", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const second = {
      ...basePipelineItemComment,
      id: "comment-2",
      createdAt: new Date("2024-02-01T00:00:00.000Z"),
    };
    mock.enqueueResults([baseItem], [basePipelineItemComment, second]);

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

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

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

  it("excludes deleted comments from result", async () => {
    // Deleted comments are removed from the database entirely (hard delete),
    // so the underlying SELECT naturally excludes them. We simulate that here.
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseItem], [basePipelineItemComment]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.comments).toHaveLength(1);
    }
  });

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