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


// GET ONE PENGUMUMAN, UNTUK TAMPIL DETAIL PENGUMUMAN
export async function GET(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;

      const data = await prisma.announcement.count({
         where: {
            id: id,
         },
      });

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

      const announcement = await prisma.announcement.findUnique({
         where: {
            id: id,
         },
         select: {
            id: true,
            title: true,
            desc: true,
         },
      });

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

      let dataFix = { ...announcement, member: {} };

      const announcementMember = await prisma.announcementMember.findMany({
         where: {
            idAnnouncement: id,
         },
         select: {
            idGroup: true,
            idDivision: true,
            Group: {
               select: {
                  name: true,
               },
            },
            Division: {
               select: {
                  name: true,
               },
            },
         },
      });

      const formatMember = announcementMember.map((v: any) => ({
         ..._.omit(v, ["Group", "Division"]),
         idGroup: v.idGroup,
         idDivision: v.idDivision,
         group: v.Group.name,
         division: v.Division.name
      }))

      dataFix.member = formatMember

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



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