import { err, ok, type CommandContext } from "@tailor-platform/erp-kit/core";
import type { Transaction } from "../generated/kysely-tailordb";
import { CommentNotFoundError, ForbiddenError } from "../lib/errors.generated";

export interface DeletePipelineItemCommentInput {
  commentId: string;
}

export async function run(
  db: Transaction,
  input: DeletePipelineItemCommentInput,
  ctx: CommandContext,
) {
  const comment = await db
    .selectFrom("PipelineItemComment")
    .selectAll()
    .where("id", "=", input.commentId)
    .forUpdate()
    .executeTakeFirst();

  if (!comment) {
    return err(new CommentNotFoundError(input.commentId));
  }

  if (comment.authorUserId !== ctx.actorId) {
    return err(new ForbiddenError(input.commentId));
  }

  await db.deleteFrom("PipelineItemComment").where("id", "=", input.commentId).execute();

  return ok({ comment });
}
