import { prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { createLogUser } from "@/module/user";
import { NextResponse } from "next/server";


// KIRIM KOMENTAR DISKUSI UMUM
export async function POST(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params
      const { desc } = (await request.json());

      const user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }

      const cek = await prisma.discussion.count({
         where: {
            id,
            isActive: true
         }
      })

      if (cek == 0) {
         return NextResponse.json({ success: false, message: "Gagal menambahkan komentar, data tidak ditemukan" }, { status: 404 });
      }


      const data = await prisma.discussionComment.create({
         data: {
            comment: desc,
            idDiscussion: id,
            idUser: user.id
         }
      })

      // create log user
      const log = await createLogUser({ act: 'CREATE', desc: 'User menambah komentar pada diskusi umum', table: 'discussionComment', data: data.id })
      return NextResponse.json({ success: true, message: "Berhasil menambah komentar" }, { status: 200 });

   } catch (error) {
      console.error(error)
      return NextResponse.json({ success: false, message: "Gagal menambahkan komentar, coba lagi nanti (error: 500)" })
   }
}