import { prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import _, { ceil } from "lodash";
import moment from "moment";
import "moment/locale/id";
import { NextResponse } from "next/server";


// HOME
export async function GET(request: Request) {
   try {
      let allData
      const user = await funGetUserByCookies()
      const { searchParams } = new URL(request.url);
      const kategori = searchParams.get("cat");

      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }

      const roleUser = user.idUserRole
      const idVillage = user.idVillage
      const idGroup = user.idGroup


      if (kategori == "kegiatan") {
         let kondisi

         // klo perbekel/developer == semua grup
         if (roleUser == "supadmin" || roleUser == "developer") {
            kondisi = {
               isActive: true,
               idVillage: idVillage,
               Group: {
                  isActive: true,
               }
            }
         } else {
            kondisi = {
               isActive: true,
               idGroup: idGroup
            }
         }
         //  else if (roleUser == "admin" || roleUser == "cosupadmin") {
         //    kondisi = {
         //       isActive: true,
         //       idGroup: idGroup
         //    }
         // } else {
         //    kondisi = {
         //       isActive: true,
         //       idGroup: idGroup,
         //       ProjectMember: {
         //          some: {
         //             idUser: user.id
         //          }
         //       }
         //    }
         // }

         const data = await prisma.project.findMany({
            skip: 0,
            take: 5,
            where: kondisi,
            select: {
               id: true,
               title: true,
               desc: true,
               status: true,
               createdAt: true,
               ProjectTask: {
                  where: {
                     isActive: true
                  },
                  select: {
                     title: true,
                     status: true
                  }
               }
            },
            orderBy: {
               updatedAt: "desc"
            }
         })

         allData = data.map((v: any) => ({
            ..._.omit(v, ["ProjectTask", "createdAt"]),
            progress: ceil((v.ProjectTask.filter((i: any) => i.status == 1).length * 100) / v.ProjectTask.length),
            createdAt: moment(v.createdAt).format("LL")
         }))

      } else if (kategori == "division") {
         let kondisi

         // klo perbekel/developer == semua grup
         if (roleUser == "supadmin" || roleUser == "developer") {
            kondisi = {
               isActive: true,
               idVillage: idVillage,
               Group: {
                  isActive: true,
               }
            }
         } else {
            kondisi = {
               isActive: true,
               idGroup: idGroup
            }
         }
         // else if (roleUser == "admin" || roleUser == "cosupadmin") {
         //    kondisi = {
         //       isActive: true,
         //       idGroup: idGroup
         //    }
         // } else {
         //    kondisi = {
         //       isActive: true,
         //       idGroup: idGroup,
         //       DivisionMember: {
         //          some: {
         //             idUser: user.id
         //          }
         //       }
         //    }
         // }

         const data = await prisma.division.findMany({
            where: kondisi,
            select: {
               id: true,
               name: true,
               DivisionProject: {
                  where: {
                     isActive: true,
                     NOT: {
                        status: 3
                     }
                  }
               }
            },
         })

         const format = data.map((v: any) => ({
            ..._.omit(v, ["DivisionProject"]),
            jumlah: v.DivisionProject.length,
         }))

         const filter = format.filter((v: any) => v.jumlah > 0)

         allData = _.orderBy(filter, 'jumlah', 'desc').slice(0, 5)

      } else if (kategori == "progress") {
         let kondisi

         // klo perbekel/developer == semua grup
         if (roleUser == "supadmin" || roleUser == "developer") {
            kondisi = {
               isActive: true,
               idVillage: idVillage,
               Group: {
                  isActive: true,
               }
            }
            // kondisi = {
            //    isActive: true,
            //    Division: {
            //       isActive: true,
            //       idVillage: idVillage,
            //       Group: {
            //          isActive: true,
            //       }
            //    }
            // }
         } else {
            kondisi = {
               isActive: true,
               idGroup: idGroup
            }
         }
         // else if (roleUser == "admin" || roleUser == "cosupadmin") {
         //    kondisi = {
         //       isActive: true,
         //       Division: {
         //          isActive: true,
         //          idGroup: idGroup
         //       }
         //    }
         // } else {
         //    kondisi = {
         //       isActive: true,
         //       Division: {
         //          isActive: true,
         //          DivisionMember: {
         //             some: {
         //                idUser: user.id
         //             }
         //          }
         //       }
         //    }
         // }

         const data = await prisma.project.groupBy({
            where: kondisi,
            by: ["status"],
            _count: true
         })

         const dataStatus = [{ name: 'Segera dikerjakan', status: 0 }, { name: 'Dikerjakan', status: 1 }, { name: 'Selesai dikerjakan', status: 2 }, { name: 'Dibatalkan', status: 3 }]
         const hasil: any[] = []
         let input
         for (let index = 0; index < dataStatus.length; index++) {
            const cek = data.some((i: any) => i.status == dataStatus[index].status)
            if (cek) {
               const find = ((Number(data.find((i: any) => i.status == dataStatus[index].status)?._count) * 100) / data.reduce((n, { _count }) => n + _count, 0)).toFixed(2)
               const fix = find != "100.00" ? find.substr(-2, 2) == "00" ? find.substr(0, 2) : find : "100"
               input = {
                  name: dataStatus[index].name,
                  value: fix
               }
            } else {
               input = {
                  name: dataStatus[index].name,
                  value: 0
               }
            }
            hasil.push(input)
         }

         allData = hasil

      } else if (kategori == "dokumen") {
         let kondisi

         // klo perbekel/developer == semua grup
         if (roleUser == "supadmin" || roleUser == "developer") {
            kondisi = {
               isActive: true,
               category: 'FILE',
               Division: {
                  isActive: true,
                  idVillage: idVillage,
                  Group: {
                     isActive: true,
                  }
               }
            }
         } else {
            kondisi = {
               isActive: true,
               category: 'FILE',
               Division: {
                  isActive: true,
                  idGroup: idGroup
               }
            }
         }
         // else if (roleUser == "admin" || roleUser == "cosupadmin") {
         //    kondisi = {
         //       isActive: true,
         //       category: 'FILE',
         //       Division: {
         //          isActive: true,
         //          idGroup: idGroup
         //       }
         //    }
         // } else {
         //    kondisi = {
         //       isActive: true,
         //       category: 'FILE',
         //       Division: {
         //          isActive: true,
         //          DivisionMember: {
         //             some: {
         //                idUser: user.id
         //             }
         //          }
         //       }
         //    }
         // }

         const data = await prisma.divisionDocumentFolderFile.findMany({
            where: kondisi,
         })

         const groupData = _.map(_.groupBy(data, "extension"), (v: any) => ({
            file: v[0].extension,
            jumlah: v.length,
         }))

         const image = ['jpg', 'jpeg', 'png', 'heic']


         let hasilImage = {
            name: 'Gambar',
            value: 0
         }

         let hasilFile = {
            name: 'Dokumen',
            value: 0
         }

         groupData.map((v: any) => {
            if (image.some((i: any) => i == v.file)) {
               hasilImage = {
                  name: 'Gambar',
                  value: hasilImage.value + v.jumlah
               }
            } else {
               hasilFile = {
                  name: 'Dokumen',
                  value: hasilFile.value + v.jumlah
               }
            }
         })

         allData = [hasilImage, hasilFile]

      } else if (kategori == "event") {
         let kondisi

         // klo perbekel/developer == semua grup
         if (roleUser == "supadmin" || roleUser == "developer") {
            kondisi = {
               isActive: true,
               dateStart: new Date(),
               Division: {
                  isActive: true,
                  idVillage: idVillage,
                  Group: {
                     isActive: true,
                  }
               },
               DivisionCalendar: {
                  isActive: true
               },
            }
         } else {
            kondisi = {
               isActive: true,
               dateStart: new Date(),
               Division: {
                  isActive: true,
                  idGroup: idGroup
               },
               DivisionCalendar: {
                  isActive: true
               },
            }
         }


         const data = await prisma.divisionCalendarReminder.findMany({
            skip: 0,
            take: 5,
            where: kondisi,
            select: {
               id: true,
               idCalendar: true,
               timeStart: true,
               dateStart: true,
               timeEnd: true,
               dateEnd: true,
               createdAt: true,
               status: true,
               idDivision: true,
               DivisionCalendar: {
                  select: {
                     title: true,
                     desc: true,
                     User: {
                        select: {
                           name: true
                        }
                     }
                  }
               }
            },
            orderBy: [
               {
                  dateStart: 'asc'
               },
               {
                  timeStart: 'asc'
               },
               {
                  timeEnd: 'asc'
               }
            ]
         })

         allData = data.map((v: any) => ({
            ..._.omit(v, ["DivisionCalendar", "User"]),
            user_name: v.DivisionCalendar.User.name,
            title: v.DivisionCalendar.title,
            timeStart: moment.utc(v.timeStart).format('HH:mm'),
            timeEnd: moment.utc(v.timeEnd).format('HH:mm')
         }))

      } else if (kategori == "discussion") {
         let kondisi

         // klo perbekel/developer == semua grup
         if (roleUser == "supadmin" || roleUser == "developer") {
            kondisi = {
               isActive: true,
               status: 1,
               Division: {
                  isActive: true,
                  idVillage: idVillage,
                  Group: {
                     isActive: true,
                  }
               }
            }
         } else {
            kondisi = {
               isActive: true,
               status: 1,
               Division: {
                  idGroup: idGroup,
                  isActive: true
               }
            }
         }
         // else if (roleUser == "admin" || roleUser == "cosupadmin") {
         //    kondisi = {
         //       isActive: true,
         //       status: 1,
         //       Division: {
         //          idGroup: idGroup,
         //          isActive: true
         //       }
         //    }
         // } else {
         //    kondisi = {
         //       isActive: true,
         //       status: 1,
         //       Division: {
         //          isActive: true,
         //          DivisionMember: {
         //             some: {
         //                idUser: user.id
         //             }
         //          }
         //       }
         //    }
         // }

         const data = await prisma.divisionDisscussion.findMany({
            skip: 0,
            take: 5,
            where: kondisi,
            select: {
               id: true,
               idDivision: true,
               title: true,
               desc: true,
               createdAt: true,
               User: {
                  select: {
                     name: true
                  }
               }
            },
            orderBy: {
               createdAt: "desc"
            }
         })

         allData = data.map((v: any) => ({
            ..._.omit(v, ["createdAt", "User"]),
            date: moment(v.createdAt).format("ll"),
            user: v.User.name
         }))
      } else if (kategori == "header") {
         const total = await prisma.notifications.count({
            where: {
               isActive: true,
               isRead: false,
               idUserTo: user.id
            }
         })

         const desa = await prisma.village.findUnique({
            where: {
               id: idVillage
            }
         })

         allData = {
            totalNotif: total,
            village: desa?.name
         }
      } else if (kategori == "check-late-project") {
         const supadmin = await prisma.user.findFirst({
            where: {
               idUserRole: "supadmin",
               idVillage: idVillage
            }
         })

         const dataUmum = await prisma.projectTask.findMany({
            where: {
               Project: {
                  idVillage: idVillage,
                  isActive: true,
                  status: {
                     not: {
                        in: [2, 3]
                     }
                  }
               },
               notifikasi: false,
               isActive: true,
               status: 0,
               dateEnd: {
                  lt: new Date()
               }
            },
            select: {
               id: true,
               title: true,
               dateEnd: true,
               Project: {
                  select: {
                     id: true,
                  },
               }
            }
         })


         for (let index = 0; index < dataUmum.length; index++) {
            await prisma.projectTask.update({
               where: {
                  id: dataUmum[index].id
               },
               data: {
                  notifikasi: true
               }
            })
         }

         const pertama = dataUmum.map((v: any) => ({
            ..._.omit(v, ["Project", "title", "id", "dateEnd"]),
            idUserTo: String(supadmin?.id),
            idUserFrom: String(user.id),
            category: 'project',
            idContent: v.Project.id,
            title: `Tugas ${v.title} Telah Melewati Batas Waktu`,
            desc: `Tugas dengan deadline ${moment(v.dateEnd).format('DD-MM-yyyy')} telah berakhir. Silakan segera melakukan tindakan yang diperlukan.`
         }))

         const insertNotif = await prisma.notifications.createMany({
            data: pertama
         })

         const dataDivisi = await prisma.divisionProjectTask.findMany({
            where: {
               Division: {
                  idVillage: idVillage,
                  isActive: true
               },
               DivisionProject: {
                  isActive: true,
                  status: {
                     not: {
                        in: [2, 3]
                     }
                  }
               },
               notifikasi: false,
               isActive: true,
               status: 0,
               dateEnd: {
                  lt: new Date()
               }
            },
            select: {
               id: true,
               title: true,
               dateEnd: true,
               DivisionProject: {
                  select: {
                     id: true,
                     idDivision: true
                  },
               }
            }
         })

         for (let index = 0; index < dataDivisi.length; index++) {
            await prisma.divisionProjectTask.update({
               where: {
                  id: dataDivisi[index].id
               },
               data: {
                  notifikasi: true
               }
            })
         }

         const kedua = dataDivisi.map((v: any) => ({
            ..._.omit(v, ["DivisionProject", "title", "id", "dateEnd"]),
            idUserTo: String(supadmin?.id),
            idUserFrom: String(user.id),
            category: 'division/' + v.DivisionProject.idDivision + '/task',
            idContent: v.DivisionProject.id,
            title: `Tugas ${v.title} Telah Melewati Batas Waktu`,
            desc: `Tugas dengan deadline ${moment(v.dateEnd).format('DD-MM-yyyy')} telah berakhir. Silakan segera melakukan tindakan yang diperlukan.`
         }))

         const insertNotif2 = await prisma.notifications.createMany({
            data: kedua
         })


         const merge = [...pertama, ...kedua]

         allData = merge

      }

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

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