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

export async function GET(request: Request) {
   try {
      const { searchParams } = new URL(request.url);
      const idVillage = searchParams.get("village");
      const dStart = searchParams.get('dateStart');
      const dEnd = searchParams.get('dateEnd');

      const awalDate = moment(dStart).format('YYYY-MM-DD') + ' 00:00:01'
      const akhirDate = moment(dEnd).format('YYYY-MM-DD') + ' 23:59:59'


      const data = await prisma.userLog.findMany({
         where: {
            User: {
               idVillage: String(idVillage)
            },
            createdAt: {
               gte: new Date(awalDate),
               lte: new Date(akhirDate),
            }
         },
         select: {
            User: {
               select: {
                  name: true,
                  img: true,
                  UserRole: {
                     select: {
                        name: true
                     }
                  },
                  Group: {
                     select: {
                        name: true
                     }
                  }
               }
            },
            id: true,
            createdAt: true,
            idUser: true,
            action: true,
            desc: true,
            idContent: true,
            tbContent: true,
         }
      })

      const fixData = data.map((v: any) => ({
         ..._.omit(v, ["createdAt", "User"]),
         createdAt: moment(v.createdAt).format("lll").replace("pukul", ""),
         userName: v.User.name,
         userImg: v.User.img,
         userRole: v.User.UserRole.name,
         userGroup: v.User.Group.name
      }))

      return NextResponse.json({ success: true, message: "Berhasil mendapatkan data", data: fixData }, { status: 200 });

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