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


// GET ALL DATA DIVISI == LIST DATA DIVISI
export async function GET(request: Request) {
   try {
      let grup

      const { searchParams } = new URL(request.url);
      const idGroup = searchParams.get("group");
      const kategori = searchParams.get("cat");
      const name = searchParams.get('search');
      const page = searchParams.get('page');
      const active = searchParams.get("active");
      const user = searchParams.get('user');
      const dataSkip = Number(page) * 10 - 10;

      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 villaId = userMobile.idVillage
      const roleUser = userMobile.idUserRole


      if (idGroup == "null" || idGroup == undefined || idGroup == "" || idGroup == "undefined" || idGroup == null) {
         grup = userMobile.idGroup
      } else {
         grup = idGroup
      }


      // JIKA (ROLE BUKAN USER DAN COADMIN) ATAU SEMUA ROLE DG KATEGORI == SEMUA
      let kondisi: any = {
         isActive: active == 'false' ? false : true,
         idVillage: String(villaId),
         idGroup: grup,
         name: {
            contains: (name == undefined || name == "null") ? "" : name,
            mode: "insensitive"
         }
      }


      // JIKA ROLE = USER ATAU COADMIN DAN KATEGORI != SEMUA (DIVISI SAYA)
      if (roleUser != "supadmin" && roleUser != "developer" && roleUser != "cosupadmin" && roleUser != "admin") {
         if (kategori != "semua") {
            kondisi = {
               isActive: active == 'false' ? false : true,
               idVillage: String(villaId),
               idGroup: grup,
               name: {
                  contains: (name == undefined || name == "null") ? "" : name,
                  mode: "insensitive"
               },
               DivisionMember: {
                  some: {
                     isActive: true,
                     idUser: String(userMobile.id)
                  }
               }
            }
         }
      }

      const totalData = await prisma.division.count({
         where: kondisi
      })

      const data = await prisma.division.findMany({
         skip: dataSkip,
         take: 10,
         where: kondisi,
         select: {
            id: true,
            name: true,
            desc: true,
            DivisionMember: {
               where: {
                  isActive: true
               },
               select: {
                  idUser: true
               }
            }
         },
         orderBy: {
            createdAt: 'desc'
         }
      });

      const allData = data.map((v: any) => ({
         ..._.omit(v, ["DivisionMember"]),
         jumlah_member: v.DivisionMember.length
      }))


      const filter = await prisma.group.findUnique({
         where: {
            id: grup
         },
         select: {
            id: true,
            name: true
         }
      })


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



// CREATE DATA DIVISI
export async function POST(request: Request) {
   try {

      const sent = (await request.json())
      const user = sent.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 userId = userMobile.id
      const userRoleLogin = userMobile.idUserRole

      let fixGroup
      if (sent.data.idGroup == "null" || sent.data.idGroup == undefined || sent.data.idGroup == "") {
         fixGroup = userMobile.idGroup
      } else {
         fixGroup = sent.data.idGroup
      }



      const data = await prisma.division.create({
         data: {
            name: sent.data.name,
            idVillage: String(userMobile.idVillage),
            idGroup: fixGroup,
            desc: sent.data.desc,
            createdBy: String(userMobile.id)
         },
         select: {
            id: true
         }
      })


      const dataMember = sent.member.map((v: any) => ({
         ..._.omit(v, ["idUser", "name", "img"]),
         idUser: v.idUser,
         idDivision: data.id,
         isAdmin: sent.admin.some((i: any) => i == v.idUser)
      }))

      const insertMember = await prisma.divisionMember.createMany({
         data: dataMember
      })


      // mengirim notifikasi
      // dataFCM untuk push notifikasi mobile
      // datanotif untuk realtime notifikasi
      // datapush untuk web push notifikasi ketika aplikasi tidak aktif
      const dataNotif = sent.member.map((v: any) => ({
         ..._.omit(v, ["idUser", "name", "img"]),
         idUserTo: v.idUser,
         idUserFrom: userId,
         category: 'division',
         idContent: data.id,
         title: 'Divisi Baru',
         desc: `Divisi ${sent.data.name} telah dibuat. Silakan periksa detailnya.`
      }))

      const selectUser = await prisma.divisionMember.findMany({
         where: {
            isActive: true,
            idDivision: data.id
         },
         select: {
            idUser: true,
            User: {
               select: {
                  Subscribe: {
                     select: {
                        subscription: true
                     }
                  },
                  TokenDeviceUser: {
                     select: {
                        token: true
                     }
                  }
               }
            }
         }
      })

      const dataFCM = selectUser.map((v: any) => ({
         ..._.omit(v, ["idUser", "User", "Subscribe", "TokenDeviceUser"]),
         tokens: v.User.TokenDeviceUser.map((v: any) => v.token)
      }))
      const tokenDup = dataFCM.filter((v: any) => v.tokens.length > 0).map((v: any) => v.tokens).flat();

      const dataPush = selectUser.map((v: any) => ({
         ..._.omit(v, ["idUser", "User", "Subscribe"]),
         idUser: v.idUser,
         subscription: v.User.Subscribe?.subscription,
      }))

      if (userRoleLogin != "supadmin") {
         const perbekel = await prisma.user.findFirst({
            where: {
               isActive: true,
               idUserRole: "supadmin",
               idVillage: user.idVillage
            },
            select: {
               id: true,
               Subscribe: {
                  select: {
                     subscription: true
                  }
               },
               TokenDeviceUser: {
                  select: {
                     token: true
                  }
               }
            }
         })

         tokenDup.push(perbekel?.TokenDeviceUser.map((v: any) => v.token).flat())

         dataNotif.push({
            idUserTo: perbekel?.id,
            idUserFrom: userId,
            category: 'division',
            idContent: data.id,
            title: 'Divisi Baru',
            desc: `Divisi ${sent.data.name} telah dibuat. Silakan periksa detailnya.`
         })

         dataPush.push({
            idUser: perbekel?.id,
            subscription: perbekel?.Subscribe?.subscription
         })

      } else {
         const atasanGroup = await prisma.user.findMany({
            where: {
               isActive: true,
               idGroup: sent.data.idGroup,
               AND: {
                  OR: [
                     { idUserRole: 'cosupadmin' },
                     { idUserRole: 'admin' },
                  ]
               }
            },
            select: {
               id: true,
               Subscribe: {
                  select: {
                     subscription: true
                  }
               },
               TokenDeviceUser: {
                  select: {
                     token: true
                  }
               }
            }
         })

         const omitFCM = atasanGroup.map((v: any) => ({
            ..._.omit(v, ["id", "Subscribe", "TokenDeviceUser"]),
            tokens: v.TokenDeviceUser.map((v: any) => v.token)
         }))

         const omitData = atasanGroup.map((v: any) => ({
            ..._.omit(v, ["id", "Subscribe", "TokenDeviceUser"]),
            idUserTo: v.id,
            idUserFrom: userId,
            category: 'division',
            idContent: data.id,
            title: 'Divisi Baru',
            desc: `Divisi ${sent.data.name} telah dibuat. Silakan periksa detailnya.`
         }))

         const omitPush = atasanGroup.map((v: any) => ({
            ..._.omit(v, ["id", "Subscribe", "TokenDeviceUser"]),
            idUser: v.id,
            subscription: v.Subscribe?.subscription,
         }))

         dataNotif.push(...omitData)
         dataPush.push(...omitPush)
         tokenDup.push(...omitFCM.map((v: any) => v.tokens).flat())
      }

      const dataNotifFilter = dataNotif.filter((v: any) => v.idUserTo != undefined && v.idUserTo != null && v.idUserTo != "" && v.idUserTo != userId)
      const dataNotifFilterUnique = dataNotifFilter
         .filter((v: any, index: number, self: any[]) =>
            index === self.findIndex((t: any) => t.idUserTo == v.idUserTo)
         )

      const pushNotif = dataPush.filter((item) => item.subscription != undefined)

      const sendWebPush = await funSendWebPush({ sub: pushNotif, message: { title: 'Divisi Baru', body: `Divisi ${sent.data.name} telah dibuat. Silakan periksa detailnya.` } })
      const insertNotif = await prisma.notifications.createMany({
         data: dataNotifFilterUnique
      })

      const tokenUnique = [...new Set(tokenDup.flat())].filter((v: any) => v != undefined && v != null && v != "");
      await sendFCMNotificationMany({
         token: tokenUnique,
         title: "Divisi Baru",
         body: `Divisi ${sent.data.name} telah dibuat. Silakan periksa detailnya.`,
         data: { id: data.id, category: "division", content: data.id }
      })

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

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


// CEK DATA DIVISI (NAME DI DESA DAN GROUP YG SAMA)
export async function PUT(request: Request) {
   try {

      const sent = (await request.json())
      const user = sent.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 });
      }

      let fixGroup
      if (sent.data.idGroup == "null" || sent.data.idGroup == undefined || sent.data.idGroup == "") {
         fixGroup = userMobile.idGroup
      } else {
         fixGroup = sent.data.idGroup
      }

      const checkData = await prisma.division.count({
         where: {
            name: {
               equals: sent.data.name,
               mode: "insensitive"
            },
            idGroup: fixGroup,
            idVillage: String(userMobile.idVillage)
         }
      })

      if (checkData > 0) {
         return NextResponse.json({ success: true, message: "Divisi dengan nama ini sudah ada", available: false }, { status: 200 });
      }

      return NextResponse.json({ success: true, message: "Berhasil cek data divisi", available: true }, { status: 200 });
   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal menambahkan divisi, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
   }
};