import { prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { createLogUser } from "@/module/user";
import _ from "lodash";
import moment from "moment";
import { NextResponse } from "next/server";
import "moment/locale/id";



// GET ALL DISCUSSION GENERAL
export async function GET(request: Request) {
   try {
      const user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }

      let grup
      const roleUser = user.idUserRole
      const villageId = user.idVillage
      const userId = user.id
      const { searchParams } = new URL(request.url);
      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 == "") {
         grup = user.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: 404 });
      }

      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 GENERALE
export async function POST(request: Request) {
   try {
      const user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }

      const userId = user.id
      const userRoleLogin = user.idUserRole
      const { idGroup, title, desc, member } = (await request.json());

      const data = await prisma.discussion.create({
         data: {
            idVillage: String(user.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
      })

      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: user.idVillage
            },
            select: {
               id: true,
               Subscribe: {
                  select: {
                     subscription: true
                  }
               }
            }
         })

         dataNotif.push({
            idUserTo: perbekel?.id,
            idUserFrom: userId,
            category: 'discussion',
            idContent: data.id,
            title: 'Diskusi Umum Baru',
            desc: title
         })
      }

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


      // create log user
      const log = await createLogUser({ act: 'CREATE', desc: 'User membuat data diskusi umum', table: 'discussion', data: data.id })
      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 });
   }
}