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

export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const villageId = searchParams.get("desa");
      const isActive = searchParams.get("active");
      const search = searchParams.get('search');
      const page = searchParams.get('page')
      const get = searchParams.get('get')

      let getFix = 10;
      if (get == null || get == undefined || get == "" || _.isNaN(Number(get))) {
         getFix = 10;
      } else {
         getFix = Number(get);
      }

      const dataSkip = page == null || page == undefined ? 0 : Number(page) * getFix - getFix;

      const data = await prisma.group.findMany({
         skip: dataSkip,
         take: getFix,
         where: {
            isActive: isActive == 'false' ? false : true,
            idVillage: String(villageId),
            name: {
               contains: (search == undefined || search == null) ? "" : search,
               mode: "insensitive"
            }
         },
         orderBy: {
            name: 'asc'
         }
      });

      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 });
   }
}