import { err, ok, type ReadonlyDB } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";
import { ItemNotFoundError } from "../lib/errors.generated";

export interface ListPipelineItemCommentsByItemInput {
  itemId: string;
}

export async function run(db: ReadonlyDB<DB>, input: ListPipelineItemCommentsByItemInput) {
  const item = await db
    .selectFrom("PipelineItem")
    .selectAll()
    .where("id", "=", input.itemId)
    .executeTakeFirst();

  if (!item) {
    return err(new ItemNotFoundError(input.itemId));
  }

  const comments = await db
    .selectFrom("PipelineItemComment")
    .selectAll()
    .where("itemId", "=", input.itemId)
    .orderBy("createdAt", "asc")
    .execute();

  return ok({ comments });
}
