"use server";

import { appRoutes } from "@/config";
import { commentSchema } from "@/lib/validation/zod/comment";
import { api } from "@/trpc/server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import { actionClient } from ".";

export const createComment = actionClient
  .schema(
    z.object({
      comment: commentSchema,
      articleId: z.string(),
    }),
  )
  .action(async ({ parsedInput: { comment, articleId } }) => {
    const commentId = await api.comment.create({
      comment,
      articleId,
    });
    if (!commentId)
      return {
        failure: "Incorrect credentials",
      };
    revalidatePath(appRoutes.article(articleId));
    return {
      data: commentId,
      success: true,
    };
  });

export async function deleteComment(commentId: string) {
  const articleId = (
    await api.comment.delete({
      commentId,
    })
  )?.articleId;
  if (!articleId)
    return {
      success: false,
      message: "Error deleting comment",
    };
  revalidatePath(appRoutes.article(articleId));
  return {
    success: true,
  };
}
