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


// GET MEMBER BY ID
export async function GET(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;
        const { searchParams } = new URL(request.url);
        const name = searchParams.get('search')
        const user = searchParams.get('user')

        const userMobile = await funGetUserById({ id: String(user) })

        if (userMobile.id == "null" || userMobile.id == undefined || userMobile.id == "") {
            return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
        }

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

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

        const member = await prisma.divisionMember.findMany({
            where: {
                idDivision: String(id),
                isActive: true,
                User: {
                    name: {
                        contains: (name == undefined || name == null) ? "" : name,
                        mode: "insensitive",
                    }
                }
            },
            select: {
                id: true,
                isAdmin: true,
                isLeader: 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
        }))

        return NextResponse.json({ success: true, data: fixMember })

    } catch (error) {
        return NextResponse.json({ success: false, message: "Gagal mendapatkan anggota, data tidak ditemukan (error: 500)", }, { status: 500 });
    }
}