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

// GET HISTORY 
export async function GET(request: Request) {
    try {
        const { searchParams } = new URL(request.url);
        const idDivision = searchParams.get("division");
        const name = searchParams.get('search');
        const page = searchParams.get('page');
        const user = searchParams.get('user');
        const dataSkip = Number(page) * 10 - 10;

        const userMobile = await funGetUserById({ id: String(user) })
        if (userMobile.id == "null" || userMobile.id == undefined || userMobile.id == "") {
            return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
        }

        if (idDivision != "null" && idDivision != null && idDivision != undefined && idDivision != "" && idDivision != "undefined") {
            const cekDivision = await prisma.division.count({
                where: {
                    id: idDivision,
                    // isActive: true
                }
            })

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

            const data = await prisma.divisionCalendarReminder.findMany({
                skip: dataSkip,
                take: 10,
                where: {
                    isActive: true,
                    idDivision: idDivision,
                    dateEnd: {
                        lte: new Date()
                    },
                    DivisionCalendar: {
                        title: {
                            contains: (name == undefined || name == "null") ? "" : name,
                            mode: "insensitive"
                        },
                        isActive: true
                    }

                },
                select: {
                    id: true,
                    timeStart: true,
                    dateStart: true,
                    timeEnd: true,
                    DivisionCalendar: {
                        select: {
                            title: true,
                        }
                    }
                },
                orderBy: [
                    {
                        dateStart: 'desc'
                    },
                    {
                        timeStart: 'asc'
                    },
                    {
                        timeEnd: 'asc'
                    }
                ]
            });

            const allOmit = data.map((v: any) => ({
                ..._.omit(v, ["DivisionCalendar", "dateStart"]),
                dateStart: moment.utc(v.dateStart).format("DD MMM"),
                year: moment.utc(v.dateStart).format("YYYY"),
                title: v.DivisionCalendar.title,
            }))


            // groupBy untuk dateStart
            const groupByDateStart = _.groupBy(allOmit, 'dateStart');

            const result = Object.keys(groupByDateStart).map(key => {
                const obj = groupByDateStart[key];
                const year = obj[0].year
                const data = obj.map((v: any) => ({
                    id: v.id,
                    title: v.title,
                    timeEnd: moment.utc(v.timeEnd).format('HH:mm'),
                    timeStart: moment.utc(v.timeStart).format('HH:mm')
                }))
                return {
                    dateStart: key,
                    year: year,
                    data: data
                }
            })

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

        } else {
            return NextResponse.json({ success: false, message: "Gagal mendapatkan riwayat acara kalender, coba lagi nanti" }, { status: 200 });

        }

    } catch (error) {
        console.error(error)
        return NextResponse.json({ success: false, message: "Gagal mendapatkan riwayat acara kalender, coba lagi nanti (error: 500)" }, { status: 500 });
    }
}