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

// GET ONE MEMBER / USER 
export async function GET(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;

      const users = await prisma.user.findUnique({
         where: {
            id: id,
         },
         select: {
            id: true,
            nik: true,
            name: true,
            phone: true,
            email: true,
            gender: true,
            img: true,
            idGroup: true,
            isActive: true,
            idPosition: true,
            createdAt: true,
            updatedAt: true,
            UserRole: {
               select: {
                  name: true,
                  id: true
               }
            },
            Position: {
               select: {
                  name: true,
                  id: true
               },
            },
            Group: {
               select: {
                  name: true,
                  id: true
               },
            },
         },
      });

      const { ...userData } = users;
      const group = users?.Group.name
      const position = users?.Position?.name
      const idUserRole = users?.UserRole.id
      const phone = '+62' + users?.phone
      const role = users?.UserRole.name
      const gender = users?.gender == "F" ? "Perempuan" : "Laki-Laki"

      const result = { ...userData, gender, group, position, idUserRole, phone, role };

      const omitData = _.omit(result, ["Group", "Position", "UserRole"]);



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

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