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


// GET ALL DISCUSSION GENERAL
export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const idGroup = searchParams.get("group");
      const idVillage = searchParams.get("desa");
      const search = searchParams.get('search');
      const page = searchParams.get('page');
      const status = searchParams.get('status');
      const active = searchParams.get('active');
      const get = searchParams.get('get')


      let getFix = 10;
      if (get == null || get == undefined || get == "" || _.isNaN(Number(get))) {
         getFix = 10;
      } else {
         getFix = Number(get);
      }

      const dataSkip = page == null || page == undefined ? 0 : Number(page) * getFix - getFix;

      let kondisi: any = {
         isActive: active == "false" ? false : true,
         status: status == "close" ? 2 : 1,
         idVillage: String(idVillage),
         title: {
            contains: (search == undefined || search == "null") ? "" : search,
            mode: "insensitive"
         },
      }

      if (idGroup != "null" && idGroup != undefined && idGroup != "") {
         kondisi = {
            ...kondisi,
            idGroup: String(idGroup)
         }
      }


      const data = await prisma.discussion.findMany({
         skip: dataSkip,
         take: getFix,
         where: kondisi,
         orderBy: [
            {
               status: 'desc'
            },
            {
               createdAt: 'desc'
            }
         ],

         select: {
            id: true,
            title: true,
            desc: true,
            status: true,
            createdAt: true,
            DiscussionComment: {
               select: {
                  id: true,
               }
            },
            Group: {
               select: {
                  name: true,
               }
            }
         }
      });

      const fixData = data.map((v: any) => ({
         ..._.omit(v, ["DiscussionComment", "status", "Group"]),
         totalKomentar: v.DiscussionComment.length,
         status: v.status == 1 ? "Open" : "Close",
         group: v.Group.name,
      }))

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