import { prisma } from "@/module/_global";
import { NextResponse } from "next/server";

// GET ONE DISCUSSION BY ID
export async function GET(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params

      const cek = await prisma.divisionDisscussion.count({
         where: { id }
      })

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

      const data = await prisma.divisionDisscussion.findUnique({
         where: { id },
         select: {
            isActive: true,
            id: true,
            desc: true,
            status: true,
            createdAt: true,
            idDivision: true,
            Division: {
               select: {
                  name: true,
               }
            },
            User: { select: { name: true, img: true } },
            DivisionDisscussionComment: {
               select: {
                  id: true,
                  comment: true,
                  createdAt: true,
                  User: { select: { name: true, img: true } }
               }
            },
         }
      });

      if (!data) {
         return NextResponse.json(
            { success: false, message: "Diskusi tidak ditemukan" },
            { status: 404 }
         );
      }

      // ambil nama creator
      const createdBy = data.User.name;
      const status = data.status == 1 ? "Open" : "Close"
      const division = data.Division.name

      // mapping komentar → hilangkan nested User
      const komentar = data.DivisionDisscussionComment.map((comment: any) => ({
         id: comment.id,
         comment: comment.comment,
         createdAt: comment.createdAt,
         username: comment.User.name,
         userimg: comment.User.img,
      }));

      // bentuk hasil akhir sesuai request
      const result = {
         id: data.id,
         idDivision: data.idDivision,
         division,
         isActive: data.isActive,
         desc: data.desc,
         status,
         createdAt: data.createdAt,
         createdBy,
         komentar,
      };

      return NextResponse.json(
         { success: true, message: "Berhasil mendapatkan diskusi", data: result },
         { status: 200 }
      );

   } catch (error) {
      console.error(error);
      return NextResponse.json(
         { success: false, message: "Gagal mendapatkan diskusi, coba lagi nanti (error: 500)", reason: (error as Error).message },
         { status: 500 }
      );
   }
}
