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


// GET ALL DATA TUGAS DIVISI
export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const name = searchParams.get('search');
      const divisi = searchParams.get('division');
      const status = searchParams.get('status');
      const page = searchParams.get('page');
      const user = searchParams.get('user');
      const dataSkip = Number(page) * 10 - 10;
      const tahun = searchParams.get("year");

      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 cek = await prisma.division.count({
         where: {
            // isActive: true,
            id: String(divisi)
         }
      })

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

      let tahunFilter = String(tahun)
      if (tahunFilter == "null" || tahunFilter == undefined || tahunFilter == "" || tahunFilter == "undefined") {
         tahunFilter = new Date().getFullYear().toString();
      }


      const startTahun = new Date(`${tahunFilter}-01-01T00:00:00.000Z`);
      const endTahun = new Date(`${parseInt(tahunFilter) + 1}-01-01T00:00:00.000Z`);

      const data = await prisma.divisionProject.findMany({
         skip: dataSkip,
         take: 10,
         where: {
            isActive: true,
            idDivision: String(divisi),
            status: (status == "0" || status == "1" || status == "2" || status == "3") ? Number(status) : 0,
            title: {
               contains: (name == undefined || name == "null") ? "" : name,
               mode: "insensitive"
            },
            createdAt: {
               gte: startTahun,
               lt: endTahun
            }
         },
         select: {
            id: true,
            title: true,
            desc: true,
            status: true,
            DivisionProjectTask: {
               where: {
                  isActive: true
               },
               select: {
                  title: true,
                  status: true
               }
            },
            DivisionProjectMember: {
               where: {
                  isActive: true
               },
               select: {
                  idUser: true
               }
            }
         },
         orderBy: {
            createdAt: "desc"
         }
      });

      const formatData = data.map((v: any) => ({
         ..._.omit(v, ["DivisionProjectTask", "DivisionProjectMember"]),
         progress: ceil((v.DivisionProjectTask.filter((i: any) => i.status == 1).length * 100) / v.DivisionProjectTask.length),
         member: v.DivisionProjectMember.length
      }))

      const totalData = await prisma.divisionProject.count({
         where: {
            isActive: true,
            idDivision: String(divisi),
            status: (status == "0" || status == "1" || status == "2" || status == "3") ? Number(status) : 0,
            title: {
               contains: (name == undefined || name == "null") ? "" : name,
               mode: "insensitive"
            },
            createdAt: {
               gte: startTahun,
               lt: endTahun
            }
         }
      })

      return NextResponse.json({ success: true, message: "Berhasil mendapatkan divisi", data: formatData, tahun: tahunFilter, total: totalData }, { 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 PROJECT TASK DIVISION
export async function POST(request: Request) {
   try {
      const body = await request.formData()
      const dataBody = body.get("data")
      const cekFile = body.has("file0")
      const { title, task, member, idDivision, user } = JSON.parse(dataBody as string)

      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


      const cek = await prisma.division.count({
         where: {
            isActive: true,
            id: idDivision
         }
      })

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

      const data = await prisma.divisionProject.create({
         data: {
            idDivision: idDivision,
            title: title,
            desc: ''
         },
         select: {
            id: true
         }
      })


      if (task.length > 0) {
         const dataTask = task.map((v: any) => ({
            ..._.omit(v, ["dateStart", "dateEnd", "title", "dateStartFix", "dateEndFix", "dataDetail"]),
            idDivision: idDivision,
            idProject: data.id,
            title: v.title,
            dateStart: new Date(v.dateStartFix),
            dateEnd: new Date(v.dateEndFix),
         }))

         let dataDetailFix = []
         for (let i = 0; i < dataTask.length; i++) {
            const insertTask = await prisma.divisionProjectTask.create({
               data: dataTask[i],
               select: {
                  id: true
               }
            })
            const dataDetail = task[i].dataDetail.map((v: any) => ({
               ...v,
               idTask: insertTask.id,
               date: new Date(v.date),
               timeStart: v.timeStart == null ? null : new Date(new Date('1970-01-01 ' + v.timeStart).getTime() - (new Date('1970-01-01 ' + v.timeStart).getTimezoneOffset() * 60000)).toISOString(),
               timeEnd: v.timeEnd == null ? null : new Date(new Date('1970-01-01 ' + v.timeEnd).getTime() - (new Date('1970-01-01 ' + v.timeEnd).getTimezoneOffset() * 60000)).toISOString(),
            }))
            dataDetailFix.push(...dataDetail)
         }

         const insertDetail = await prisma.divisionProjectTaskDetail.createMany({
            data: dataDetailFix
         })
      }

      if (member.length > 0) {
         const dataMember = member.map((v: any) => ({
            ..._.omit(v, ["idUser", "name", "img"]),
            idDivision: idDivision,
            idProject: data.id,
            idUser: v.idUser,
         }))

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



      let fileFix: any[] = []

      if (cekFile) {
         for (var pair of body.entries()) {
            if (String(pair[0]).substring(0, 4) == "file") {
               const file = body.get(pair[0]) as File
               const fExt = file.name.split(".").pop()
               const fName = file.name.replace("." + fExt, "")

               const upload = await funUploadFile({ file: file, dirId: DIR.task })
               if (upload.success) {
                  const insertToContainer = await prisma.containerFileDivision.create({
                     data: {
                        idDivision: idDivision,
                        name: fName,
                        extension: String(fExt),
                        idStorage: upload.data.id
                     },
                     select: {
                        id: true
                     }
                  })

                  const dataFile = {
                     idProject: data.id,
                     idDivision: idDivision,
                     idFile: insertToContainer.id,
                     createdBy: userMobile.id,
                  }

                  fileFix.push(dataFile)
               }
            }
         }

         const insertFile = await prisma.divisionProjectFile.createMany({
            data: fileFix
         })
      }

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

      // mengirim notifikasi
      // dataFCM untuk push notifikasi mobile
      // datanotif untuk realtime notifikasi
      // datapush untuk web push notifikasi ketika aplikasi tidak aktif
      const dataFCM = memberDivision.map((v: any) => ({
         ..._.omit(v, ["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 dataNotif = memberDivision.map((v: any) => ({
         ..._.omit(v, ["User", "Subscribe", "TokenDeviceUser"]),
         idUserTo: v.User.id,
         idUserFrom: String(userMobile.id),
         category: 'division/' + idDivision + '/task',
         idContent: data.id,
         title: 'Tugas Divisi Baru',
         desc: title
      }))

      const dataPush = memberDivision.map((v: any) => ({
         ..._.omit(v, ["User", "Subscribe", "TokenDeviceUser"]),
         idUser: v.User.id,
         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/' + idDivision + '/task',
            idContent: data.id,
            title: 'Tugas Divisi Baru',
            desc: title
         })

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

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

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

         dataNotif.push({
            idUserTo: ketuaGrup?.id,
            idUserFrom: userId,
            category: 'division/' + idDivision + '/task',
            idContent: data.id,
            title: 'Tugas Divisi Baru',
            desc: title
         })

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

      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: { body: title, title: 'Tugas Divisi Baru' } })
      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: "Tugas Divisi Baru",
         body: title,
         data: { id: data.id, category: 'division/' + idDivision + '/task', content: data.id }
      })

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


      return NextResponse.json({ success: true, message: "Berhasil membuat tugas divisi", notif: dataNotif }, { status: 200 });

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