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


// KIRIM KOMENTAR DISKUSI UMUM
export async function POST(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params
      const { 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 cek = await prisma.discussion.count({
         where: {
            id,
            isActive: true
         }
      })

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


      const data = await prisma.discussionComment.create({
         data: {
            comment: desc,
            idDiscussion: id,
            idUser: userMobile.id
         }
      })

      const dataDiscussion = await prisma.discussion.findUnique({
         where: {
            id
         },
         select: {
            createdBy: true,
            User: {
               select: {
                  Subscribe: {
                     select: {
                        subscription: true
                     }
                  },
                  TokenDeviceUser: {
                     select: {
                        token: true
                     }
                  }
               }
            }
         }
      })

      const member = await prisma.discussionMember.findMany({
         where: {
            idDiscussion: id,
         },
         select: {
            idUser: true,
            User: {
               select: {
                  Subscribe: {
                     select: {
                        subscription: true
                     }
                  },
                  TokenDeviceUser: {
                     select: {
                        token: true
                     }
                  }
               }
            }
         }
      })

      const userSent = await prisma.user.findFirst({
         where: {
            id: userMobile.id
         },
         select: {
            name: true,
            img: true
         }
      })

      const memberFilter = [...member, { idUser: dataDiscussion?.createdBy, User: dataDiscussion?.User }].filter((v: any) => v.idUser != userMobile.id)
         .filter((v: any, index: number, self: any[]) =>
            index === self.findIndex((t) => t.idUser === v.idUser)
         );

      const dataFCM = memberFilter.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();

      if (userMobile.idUserRole != "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())
      }

      const commentNotif = data.comment.length > 300 ? data.comment.substring(0, 300) + '...' : data.comment;

      const tokenUnique = [...new Set(tokenDup.flat())].filter((v: any) => v != undefined && v != null && v != "");
      await sendFCMNotificationMany({
         token: tokenUnique,
         title: "Komentar Baru",
         body: `${userSent?.name}: ${commentNotif}`,
         data: { id: data.id, category: "discussion-general", content: id }
      })

      // create log user
      const log = await createLogUserMobile({ act: 'CREATE', desc: 'User menambah komentar pada diskusi umum', table: 'discussionComment', data: data.id, user: userMobile.id })
      return NextResponse.json({ success: true, message: "Berhasil menambah komentar" }, { status: 200 });

   } catch (error) {
      console.error(error)
      return NextResponse.json({ success: false, message: "Gagal menambahkan komentar, coba lagi nanti (error: 500)" })
   }
}

// EDIT KOMENTAR
export async function PUT(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params
      const { 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 cek = await prisma.discussionComment.count({
         where: {
            id,
            isActive: true
         }
      })

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


      const data = await prisma.discussionComment.update({
         where: {
            id
         },
         data: {
            comment: desc,
            isEdited: true
         }
      })

      // create log user
      const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengedit komentar pada diskusi umum', table: 'discussionComment', data: id, user: userMobile.id })
      return NextResponse.json({ success: true, message: "Berhasil mengedit komentar" }, { status: 200 });

   } catch (error) {
      console.error(error)
      return NextResponse.json({ success: false, message: "Gagal mengedit komentar, coba lagi nanti (error: 500)" })
   }
}


// HAPUS KOMENTAR
export async function DELETE(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params
      const { 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 cek = await prisma.discussionComment.count({
         where: {
            id,
            isActive: true
         }
      })

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


      const data = await prisma.discussionComment.update({
         where: {
            id
         },
         data: {
            isActive: false
         }
      })

      // create log user
      const log = await createLogUserMobile({ act: 'DELETE', desc: 'User menghapus komentar pada diskusi umum', table: 'discussionComment', data: id, user: userMobile.id })
      return NextResponse.json({ success: true, message: "Berhasil mengedit komentar" }, { status: 200 });

   } catch (error) {
      console.error(error)
      return NextResponse.json({ success: false, message: "Gagal mengedit komentar, coba lagi nanti (error: 500)" })
   }
}