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 idVillage = searchParams.get("desa")
      const idGroup = searchParams.get("group")
      const division = searchParams.get("division")
      const date = searchParams.get("date-start")
      const dateAkhir = searchParams.get("date-end")
      const kat = searchParams.get("cat")


      // CHART PROGRESS
      if (kat == "dokumen") {
         // CHART DOKUMEN
         let kondisi: any = {
            isActive: true,
            category: 'FILE',
            Division: {
               idVillage: String(idVillage)
            },
            createdAt: {
               gte: new Date(String(date)),
               lte: new Date(String(dateAkhir))
            },
         }

         if (idGroup != undefined && idGroup != null && idGroup != "") {
            kondisi = {
               isActive: true,
               category: 'FILE',
               Division: {
                  idGroup: String(idGroup)
               },
               createdAt: {
                  gte: new Date(String(date)),
                  lte: new Date(String(dateAkhir))
               },
            }
         }


         if (division != undefined && division != null && division != "") {
            kondisi = {
               ...kondisi,
               idDivision: String(division)
            }
         }


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

         const groupData = _.map(_.groupBy(dataDokumen, "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
               }
            }
         })

         const hasilDokumen = { gambar: hasilImage.value, dokumen: hasilFile.value }

         return NextResponse.json({ success: true, message: "Berhasil mendapatkan data", data: hasilDokumen }, { status: 200 });
      } else if (kat == "event") {
         // CHART EVENT
         let kondisiSelesai: any = {
            isActive: true,
            Division: {
               idVillage: String(idVillage)
            },
            DivisionCalendarReminder: {
               some: {
                  dateStart: {
                     gte: new Date(String(date)),
                     lte: new Date()
                  }
               }
            }
         }

         let kondisiComingSoon: any = {
            isActive: true,
            Division: {
               idVillage: String(idVillage)
            },
            DivisionCalendarReminder: {
               some: {
                  dateStart: {
                     gt: new Date(),
                     lte: new Date(String(dateAkhir))
                  }
               }
            }
         }

         if (idGroup != undefined && idGroup != null && idGroup != "") {
            kondisiSelesai = {
               isActive: true,
               Division: {
                  idGroup: String(idGroup)
               },
               DivisionCalendarReminder: {
                  some: {
                     dateStart: {
                        gte: new Date(String(date)),
                        lte: new Date()
                     }
                  }
               }
            }

            kondisiComingSoon = {
               isActive: true,
               Division: {
                  idGroup: String(idGroup)
               },
               DivisionCalendarReminder: {
                  some: {
                     dateStart: {
                        gt: new Date(),
                        lte: new Date(String(dateAkhir))
                     }
                  }
               }
            }
         }

         if (division != undefined && division != null && division != "") {
            kondisiSelesai = {
               ...kondisiSelesai,
               idDivision: String(division)
            }

            kondisiComingSoon = {
               ...kondisiComingSoon,
               idDivision: String(division)
            }
         }

         const eventSelesai = await prisma.divisionCalendar.count({
            where: kondisiSelesai
         })

         const eventComingSoon = await prisma.divisionCalendar.count({
            where: kondisiComingSoon
         })

         const hasilEvent = {
            selesai: eventSelesai,
            akan_datang: eventComingSoon
         }

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

      } else {
         let kondisiProgress: any = {
            isActive: true,
            Division: {
               idVillage: String(idVillage)
            },
            DivisionProjectTask: {
               some: {
                  dateStart: {
                     gte: new Date(String(date))
                  },
                  dateEnd: {
                     lte: new Date(String(dateAkhir))
                  }
               }
            }
         }

         if (idGroup != undefined && idGroup != null && idGroup != "") {
            kondisiProgress = {
               isActive: true,
               Division: {
                  idGroup: String(idGroup)
               },
               DivisionProjectTask: {
                  some: {
                     dateStart: {
                        gte: new Date(String(date))
                     },
                     dateEnd: {
                        lte: new Date(String(dateAkhir))
                     }
                  }
               }
            }
         }

         if (division != undefined && division != null && division != "") {
            kondisiProgress = {
               ...kondisiProgress,
               idDivision: String(division)
            }
         }

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

         const dataStatus = [{ name: 'Segera', status: 0 }, { name: 'Dikerjakan', status: 1 }, { name: 'Selesai', status: 2 }, { name: 'Dibatalkan', status: 3 }]
         const hasilProgres: 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
               }
            }
            hasilProgres.push(input)
         }

         const dataFixProgress = hasilProgres.reduce((acc: any, curr: any) => {
            acc[curr.name] = curr.value
            return acc
         }, {})


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