import { prisma } from "@/module/_global";
import _ from "lodash";
import "moment/locale/id";
import { NextResponse } from "next/server";
export const dynamic = 'force-dynamic'



// GET ALL PENGUMUMAN
export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const judul = searchParams.get('search');
      const page = searchParams.get('page');
      const get = searchParams.get('get');
      const villageId = searchParams.get('desa');
      const active = searchParams.get('active');

      let getFix = 0;
      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 = {
         idVillage: String(villageId),
         isActive: (active == "false" || active == undefined) ? false : true,
         title: {
            contains: (judul == undefined || judul == null) ? "" : judul,
            mode: "insensitive"
         }
      }

      const data = await prisma.announcement.findMany({
         skip: dataSkip,
         take: getFix,
         where: kondisi,
         orderBy: {
            createdAt: 'desc'
         }
      });

      return NextResponse.json({ success: true, message: "Berhasil mendapatkan pengumuman", data, }, { status: 200 });
   } catch (error) {
      console.error(error);
      return NextResponse.json({ success: false, message: "Gagal mendapatkan pengumuman, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
   }
}