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


// GET ALL DISCUSSION DIVISION ACTIVE = TRUE
export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const idDivision = searchParams.get("division");
      const name = searchParams.get('search');
      const page = searchParams.get('page');
      const status = 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 });
      }


      if (idDivision != "null" && idDivision != null && idDivision != undefined) {
         const cekDivision = await prisma.division.count({
            where: {
               id: idDivision,
               // isActive: true
            }
         })

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

         const data = await prisma.divisionDisscussion.findMany({
            skip: dataSkip,
            take: 10,
            where: {
               isActive: status == "false" ? false : true,
               idDivision: idDivision,
               desc: {
                  contains: (name == undefined || name == "null") ? "" : name,
                  mode: "insensitive"
               },
            },
            orderBy: {
               createdAt: 'desc'
            },
            select: {
               id: true,
               title: true,
               desc: true,
               status: true,
               createdAt: true,
               User: {
                  select: {
                     name: true,
                     img: true
                  }
               },
               DivisionDisscussionComment: {
                  select: {
                     id: true,
                  },
                  where: {
                     isActive: true
                  }
               }
            }
         });



         const fixData = data.map((v: any) => ({
            ..._.omit(v, ["User", "DivisionDisscussionComment", "createdAt"]),
            user_name: v.User.name,
            img: v.User.img,
            total_komentar: v.DivisionDisscussionComment.length,
            createdAt: moment(v.createdAt).format("ll")
         }))

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

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

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



// CREATE DISCUSSION
export async function POST(request: Request) {
   try {
      const contentType = request.headers.get("content-type");

      let idDivision, desc, user, cekFile, body: FormData | undefined
      if (contentType?.includes("multipart/form-data")) {
         body = await request.formData()
         const dataBody = body.get("data")
         cekFile = body.has("file0");
         ({ idDivision, desc, user } = JSON.parse(String(dataBody)));
      } else {
         ({ idDivision, 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 userRoleLogin = userMobile.idUserRole
      const userId = userMobile.id


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

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

      const data = await prisma.divisionDisscussion.create({
         data: {
            idDivision,
            desc,
            createdBy: userId
         },
         select: {
            id: true
         }
      });


      if (cekFile && body) {
         body.delete("data")
         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 = decodeURIComponent(file.name.replace("." + fExt, ""))
               const upload = await funUploadFile({ file: file, dirId: DIR.discussionDivision })
               if (upload.success) {
                  await prisma.divisionDiscussionFile.create({
                     data: {
                        idStorage: upload.data.id,
                        idDiscussion: data.id,
                        name: fName,
                        extension: String(fExt)
                     }
                  })
               }
            }
         }
      }

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

      const deskripsiNotif = desc.length > 300 ? desc.substring(0, 300) + '...' : desc;


      // 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, ["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 dataNotif = memberDivision.map((v: any) => ({
         ..._.omit(v, ["User", "Subscribe", "TokenDeviceUser"]),
         idUserTo: v.User.id,
         idUserFrom: String(userId),
         category: 'division/' + idDivision + '/discussion',
         idContent: data.id,
         title: 'Diskusi Baru',
         desc: deskripsiNotif
      }))

      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: userMobile.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 + '/discussion',
            idContent: data.id,
            title: 'Diskusi Baru',
            desc: deskripsiNotif
         })

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

      if (userRoleLogin != "cosupadmin") {
         const ketuaGrup = await prisma.user.findFirst({
            where: {
               isActive: true,
               idUserRole: "cosupadmin",
               idGroup: userMobile.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 + '/discussion',
            idContent: data.id,
            title: 'Diskusi Baru',
            desc: deskripsiNotif
         })

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

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

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