import { and, desc, eq } from "drizzle-orm";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../trpc";
import { comments, users } from "@/server/db/schema";
import { z } from "zod";
import { commentSchema } from "@/lib/validation/zod/comment";

export const commentRouter = createTRPCRouter({
  // queries
  list: publicProcedure
    .input(
      z.object({
        articleId: z.string(),
      }),
    )
    .query(
      async ({ ctx, input }) =>
        await ctx.db.query.comments.findMany({
          where: eq(comments.articleId, input.articleId),
          orderBy: desc(comments.createdAt),
          with: {
            author: {
              columns: {
                id: true,
                name: true,
                image: true,
              },
            },
          },
        }),
    ),

  // mutations
  create: protectedProcedure
    .input(
      z.object({
        comment: commentSchema,
        articleId: z.string(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const [comment] = await ctx.db
        .insert(comments)
        .values({
          ...input.comment,
          authorId: ctx.session.user.id,
          articleId: input.articleId,
        })
        .returning();
      if (!comment) return;
      const author = await ctx.db.query.users.findFirst({
        where: eq(users.id, comment.authorId),
        columns: {
          id: true,
          name: true,
          image: true,
        },
      });
      return { ...comment, author };
    }),
  delete: protectedProcedure
    .input(
      z.object({
        commentId: z.string(),
      }),
    )
    .mutation(async ({ ctx, input }) => {
      const [comment] = await ctx.db
        .delete(comments)
        .where(
          and(
            eq(comments.id, input.commentId),
            eq(comments.authorId, ctx.session.user.id),
          ),
        )
        .returning({
          id: comments.id,
          articleId: comments.articleId,
        });

      return comment;
    }),
});
