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


// GET ONE DATA DIVISI :: UNTUK TAMPIL DATA DI HALAMAN EDIT DAN INFO
export async function GET(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;
      const { searchParams } = new URL(request.url);
      const idVillage = searchParams.get("desa");

      const data = await prisma.division.findUnique({
         where: {
            id: String(id),
            idVillage: String(idVillage)
         }
      });

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

      const member = await prisma.divisionMember.findMany({
         where: {
            idDivision: String(id),
            isActive: true,
         },
         select: {
            id: true,
            isAdmin: true,
            idUser: true,
            User: {
               select: {
                  name: true,
                  img: true
               }
            }
         },
         orderBy: {
            isAdmin: 'desc',
         }
      })

      const fixMember = member.map((v: any) => ({
         ..._.omit(v, ["User"]),
         name: v.User.name,
         img: v.User.img
      }))

      const dataFix = {
         ...data,
         member: fixMember
      }


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

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