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

// GET LIST DIVISI BY ID DIVISI (CONTOH : UNTUK SHARE DOKUMEN)
export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const idDivision = searchParams.get("division");
      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 dataDivision = await prisma.division.findUnique({
         where: {
            id: String(idDivision),
            isActive: true
         }
      })

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

      const data = await prisma.division.findMany({
         where: {
            isActive: true,
            idGroup: dataDivision.idGroup,
            name: {
               contains: (name == undefined || name == "null") ? "" : name,
               mode: "insensitive"
            }
         },
         select: {
            id: true,
            name: true,
         },
         orderBy: {
            name: "asc"
         }
      });

      return NextResponse.json({ success: true, message: "Berhasil mendapatkan divisi", data }, { 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 });
   }
}