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


// GET ONE DATA DIVISI :: UNTUK TAMPIL DATA DI HALAMAN EDIT DAN INFO
export async function GET(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;
      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 data = await prisma.division.findUnique({
         where: {
            id: String(id),
            // isActive: true
         }
      });

      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,
         },
         select: {
            id: true,
            isAdmin: true,
            isLeader: true,
            idUser: true,
            User: {
               select: {
                  name: true,
                  img: true
               }
            }
         },
         orderBy: [
            {
               isAdmin: 'desc',
            },
            {
               User: {
                  name: 'asc'
               }
            }
         ]
      })

      const fixMember = member.map((v: any) => ({
         ..._.omit(v, ["User"]),
         name: v.User.name,
         img: v.User.img
      }))

      const dataFix = {
         division: data,
         member: fixMember
      }


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



// EDIT DATA DIVISI
export async function PUT(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params;
      const { name, desc, user } = (await request.json());
      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.count({
         where: {
            id: id,
         },
      });

      if (data == 0) {
         return NextResponse.json(
            {
               success: false,
               message: "Edit divisi gagal, data tidak ditemukan",
            },
            { status: 200 }
         );
      }

      const update = await prisma.division.update({
         where: {
            id: id,
         },
         data: {
            name: name,
            desc: desc
         },
      });

      // create log user
      const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengupdate data divisi', table: 'division', data: id, user: userMobile.id })

      return NextResponse.json(
         {
            success: true,
            message: "Divisi berhasil diedit",
         },
         { status: 200 }
      );
   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal mengedit divisi, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
   }
}