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


// GET ONE NOTIFIKASI PENGUMUMAN
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 });
      }

      if (user.showNotification == true) {
         const announcements = await prisma.notifications.findMany({
            skip: 0,
            take: 1,
            where: {
               isActive: true,
               idUserTo: user.id,
               isRead: false,
               category: 'announcement'
            },
            orderBy: [
               {
                  createdAt: 'desc'
               }
            ]

         });

         const allData = announcements.map((v: any) => ({
            ..._.omit(v, ["createdAt"]),
            createdAt: moment(v.createdAt).format("ll")
         }))

         await funSetCookies({ user: user.id, showNotification: false })

         if (announcements.length > 0) {
            return NextResponse.json({ show: true, message: "Berhasil mendapatkan notifikasi", data: allData }, { status: 200 });
         } else {
            return NextResponse.json({ show: false, message: "Tidak ada notifikasi pengumuman" }, { status: 200 });
         }
      } else {
         return NextResponse.json({ show: false, message: "Notifikasi telah tampil" }, { status: 200 });
      }



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