import { prisma } from "@/module/_global";
import { funGetUserByCookies } from "@/module/auth";
import { createLogUser } 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 user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }

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

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

      if (kategori == "detail") {
         const data = await prisma.discussion.findUnique({
            where: {
               id,
               // isActive: true
            },
            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,
               idUser: true,
               User: {
                  select: {
                     name: true,
                     img: true
                  }
               }
            },
            orderBy: {
               createdAt: "asc"
            }
         })

         dataFix = data.map((v: any) => ({
            ..._.omit(v, ["createdAt", "User",]),
            createdAt: moment(v.createdAt).format("lll").replace('pukul', ''),
            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
         }
      }


      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 user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }
      const { id } = context.params
      const { status } = (await request.json());
      let newStatus;
      if (status === 1) {
         newStatus = 2;
      } else if (status === 2) {
         newStatus = 1;
      } else {
         return NextResponse.json({ success: false, message: "Invalid status" }, { status: 400 });
      }

      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: 404 });
      }

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

      // create log user
      const log = await createLogUser({ act: 'UPDATE', desc: 'User mengupdate status diskusi umum', table: 'discussion', data: 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 user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }
      const { id } = context.params
      const { active } = (await request.json());

      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: 404 });
      }


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


      // create log user
      if (active) {
         const log = await createLogUser({ act: 'DELETE', desc: 'User mengaktifkan data diskusi umum', table: 'disscussion', data: id })
         return NextResponse.json({ success: true, message: "Berhasil mengaktifkan diskusi umum", user: user.id }, { status: 200 });
      } else {
         const log = await createLogUser({ act: 'DELETE', desc: 'User mengarsipkan data diskusi umum', table: 'disscussion', data: id })
         return NextResponse.json({ success: true, message: "Berhasil mengarsipkan diskusi umum", user: user.id }, { 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 user = await funGetUserByCookies()
      if (user.id == undefined) {
         return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 401 });
      }
      const { id } = context.params
      const { title, desc } = (await request.json());

      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: 404 });
      }

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

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