import { countTime, 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";


// GET ONE DETAIL DISKUSI UMUM
export async function GET(request: Request, context: { params: { id: string } }) {
   try {
      let dataFix
      const { id } = context.params
      const { searchParams } = new URL(request.url);
      const kategori = searchParams.get("cat");
      const userMobile = searchParams.get("user");

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

      if (user.id == "null" || user.id == undefined || user.id == "") {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
      }

      const cek = await prisma.discussion.count({
         where: {
            id
         }
      })

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

      if (kategori == "detail") {
         const data = await prisma.discussion.findUnique({
            where: {
               id,
            },
            select: {
               isActive: true,
               id: true,
               title: true,
               idGroup: true,
               desc: true,
               status: true,
               createdAt: true,
            }
         })

         dataFix = {
            id: data?.id,
            isActive: data?.isActive,
            idGroup: data?.idGroup,
            title: data?.title,
            desc: data?.desc,
            status: data?.status,
            createdAt: moment(data?.createdAt).format("ll"),
         }

      } else if (kategori == "komentar") {
         const data = await prisma.discussionComment.findMany({
            where: {
               idDiscussion: id,
               isActive: true
            },
            select: {
               id: true,
               comment: true,
               createdAt: true,
               updatedAt: true,
               isEdited: true,
               idUser: true,
               User: {
                  select: {
                     name: true,
                     img: true
                  }
               }
            },
            orderBy: {
               createdAt: "asc"
            }
         })

         dataFix = data.map((v: any) => ({
            ..._.omit(v, ["createdAt", "User", "updatedAt"]),
            createdAt: countTime(v.createdAt),
            updatedAt: moment(v.updatedAt).format("ll"),
            username: v.User.name,
            img: v.User.img
         }))

      } else if (kategori == "anggota") {
         const data = await prisma.discussionMember.findMany({
            where: {
               idDiscussion: id,
               isActive: true
            },
            select: {
               idUser: true,
               User: {
                  select: {
                     name: true,
                     img: true
                  }
               }
            }
         })

         dataFix = data.map((v: any) => ({
            ..._.omit(v, ["User",]),
            name: v.User.name,
            img: v.User.img
         }))
      } else if (kategori == "cek-anggota") {
         const cek = await prisma.discussionMember.count({
            where: {
               idDiscussion: id,
               isActive: true,
               idUser: user.id
            }
         })

         if (cek > 0) {
            dataFix = true
         } else {
            dataFix = false
         }
      } else if (kategori == "file") {
         const data = await prisma.discussionFile.findMany({
            where: {
               idDiscussion: id
            },
            select: {
               id: true,
               idStorage: true,
               name: true,
               extension: true
            }
         })

         dataFix = data
      }

      return NextResponse.json({ success: true, message: "Berhasil mendapatkan diskusi", data: dataFix }, { 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 });
   }
}


// OPEN OR CLOSE DISKUSI UMUM
export async function POST(request: Request, context: { params: { id: string } }) {
   try {

      const { id } = context.params
      const { status, 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 });
      }

      let newStatus;
      if (status === 1) {
         newStatus = 2;
      } else if (status === 2) {
         newStatus = 1;
      } else {
         return NextResponse.json({ success: false, message: "Invalid status" }, { status: 200 });
      }

      const data = await prisma.discussion.count({
         where: {
            id: id
         },
      });

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

      const result = await prisma.discussion.update({
         where: {
            id
         },
         data: {
            status: newStatus
         }
      });

      // create log user   
      const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengupdate status diskusi umum', table: 'discussion', data: id, user: userMobile.id })

      return NextResponse.json({ success: true, message: "Berhasil mengedit diskusi umum" }, { status: 200 });

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


// DELETE DISCUSSION
export async function DELETE(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params
      const { active, 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: id
         },
      });

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


      const data = await prisma.discussion.update({
         where: {
            id
         },
         data: {
            isActive: active
         }
      });


      // create log user
      if (active) {
         const log = await createLogUserMobile({ act: 'DELETE', desc: 'User mengaktifkan data diskusi umum', table: 'disscussion', data: id, user: userMobile.id })
         return NextResponse.json({ success: true, message: "Berhasil mengaktifkan diskusi umum" }, { status: 200 });
      } else {
         const log = await createLogUserMobile({ act: 'DELETE', desc: 'User mengarsipkan data diskusi umum', table: 'disscussion', data: id, user: userMobile.id })
         return NextResponse.json({ success: true, message: "Berhasil mengarsipkan diskusi umum" }, { status: 200 });
      }


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


// EDIT DISCUSSION
export async function PUT(request: Request, context: { params: { id: string } }) {
   try {
      const { id } = context.params
      const contentType = request.headers.get("content-type");

      let title, desc, user, oldFile: any[] = [], cekFile, body: FormData | undefined

      if (contentType?.includes("multipart/form-data")) {
         body = await request.formData()
         const dataBody = body.get("data")
         cekFile = body.has("file0");
         ({ title, desc, user, oldFile } = JSON.parse(dataBody as string))
      } else {
         ({ title, 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 data = await prisma.discussion.count({
         where: {
            id: id
         },
      });

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

      const update = await prisma.discussion.update({
         where: {
            id
         },
         data: {
            desc,
            title
         }
      });

      if (oldFile.length > 0) {
         for (let index = 0; index < oldFile.length; index++) {
            const element = oldFile[index];
            if (element.delete) {
               await prisma.discussionFile.delete({
                  where: {
                     id: element.id
                  }
               })
            }
         }
      }

      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: id,
                        name: fName,
                        extension: String(fExt)
                     }
                  })
               }
            }
         }
      }

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

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