import { prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { NextResponse } from "next/server";
export const dynamic = 'force-dynamic'
export const revalidate = true


export async function GET(request: Request) {
    try {
        const { searchParams } = new URL(request.url);
        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 role = userMobile.idUserRole
        const villaId = userMobile.idVillage
        const group = userMobile.idGroup
        let kondisi: any = {
            isActive: true,
            idVillage: String(villaId)
        }

        if (role != "supadmin" && role != "developer") {
            kondisi = {
                isActive: true,
                idVillage: String(villaId),
                id: String(group)
            }
        }

        const data = await prisma.group.findMany({
            where: kondisi,
            select: {
                id: true,
                name: true,
                Division: {
                    where: {
                        isActive: true
                    },
                    select: {
                        id: true,
                        name: true
                    }
                }
            }
        });

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

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