import { DIR, 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 GENERAL
export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const user = searchParams.get("user")
      if (user == "null" || user == undefined || user == "") {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
      }

      const userMobile = await funGetUserById({ id: user })

      let grup
      const villageId = userMobile.idVillage
      const idGroup = searchParams.get("group");
      const search = searchParams.get('search');
      const page = searchParams.get('page');
      const status = searchParams.get('active');
      const dataSkip = Number(page) * 10 - 10;

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

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

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

      const data = await prisma.discussion.findMany({
         skip: dataSkip,
         take: 10,
         where: {
            isActive: status == "false" ? false : true,
            idVillage: String(villageId),
            idGroup: grup,
            title: {
               contains: (search == undefined || search == "null") ? "" : search,
               mode: "insensitive"
            },
         },
         orderBy: [
            {
               status: 'desc'
            },
            {
               createdAt: 'desc'
            }
         ],

         select: {
            id: true,
            title: true,
            desc: true,
            status: true,
            createdAt: true,
            DiscussionComment: {
               select: {
                  id: true,
               },
               where: {
                  isActive: true
               }
            }
         }
      });

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

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

      return NextResponse.json({ success: true, message: "Berhasil mendapatkan diskusi", data: fixData, filter }, { 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 GENERAL
export async function POST(request: Request) {
   try {
      const contentType = request.headers.get("content-type");
      let idGroup, user, title, desc, member, cekFile, body: FormData | undefined
      if (contentType?.includes("multipart/form-data")) {
         body = await request.formData()
         const dataBody = body.get("data")
         cekFile = body.has("file0");
         ({ idGroup, user, title, desc, member } = JSON.parse(dataBody as string))
      } else {
         ({ idGroup, user, title, desc, member } = await request.json());
      }


      const userMobile = await funGetUserById({ id: 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 = user
      const userRoleLogin = userMobile.idUserRole

      const data = await prisma.discussion.create({
         data: {
            idVillage: String(userMobile.idVillage),
            idGroup: idGroup,
            title: title,
            desc: desc,
            createdBy: String(userId),
         },
         select: {
            id: true
         }
      });

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

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


      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.discussion })
               if (upload.success) {
                  await prisma.discussionFile.create({
                     data: {
                        idStorage: upload.data.id,
                        idDiscussion: data.id,
                        name: fName,
                        extension: String(fExt)
                     }
                  })
               }
            }
         }
      }

      const memberNotifMobile = await prisma.discussionMember.findMany({
         where: {
            idDiscussion: data.id
         },
         select: {
            User: {
               select: {
                  TokenDeviceUser: {
                     select: {
                        token: true
                     }
                  }
               }
            }
         }
      })

      const dataFCM = memberNotifMobile.map((v: any) => ({
         ..._.omit(v, ["User", "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 = member.map((v: any) => ({
         ..._.omit(v, ["idUser", "name", "img"]),
         idUserTo: v.idUser,
         idUserFrom: userId,
         category: 'discussion',
         idContent: data.id,
         title: 'Diskusi Umum Baru',
         desc: title
      }))

      if (userRoleLogin != "supadmin") {
         const perbekel = await prisma.user.findFirst({
            where: {
               isActive: true,
               idUserRole: "supadmin",
               idVillage: String(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: 'discussion',
            idContent: data.id,
            title: 'Diskusi Umum Baru',
            desc: title
         })
      }

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

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

      const tokenUnique = [...new Set(tokenDup.flat())].filter((v: any) => v != undefined && v != null && v != "");
      await sendFCMNotificationMany({
         token: tokenUnique,
         title: "Diskusi Umum Baru",
         body: title,
         data: { id: data.id, category: "discussion", content: data.id }
      })


      // create log user
      const log = await createLogUserMobile({ act: 'CREATE', desc: 'User membuat data diskusi umum', table: 'discussion', data: data.id, user })
      return NextResponse.json({ success: true, message: "Berhasil menambahkan diskusi umum", 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 });
   }
}