import { prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { createLogUserMobile } from "@/module/user";
import _ from "lodash";
import moment from "moment";
import "moment/locale/id";
import { NextResponse } from "next/server";
import { Frequency, RRule } from 'rrule';

// GET ONE CALENDER BY ID KALENDER REMINDER
export async function GET(request: Request, context: { params: { id: string } }) {
    try {

        const { id } = context.params
        const { searchParams } = new URL(request.url);
        const user = searchParams.get("user");
        const kategori = searchParams.get("cat");

        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 });
        }

        const cek = await prisma.divisionCalendarReminder.count({
            where: {
                id: id
            }
        })

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

        const data: any = await prisma.divisionCalendarReminder.findUnique({
            where: {
                id: id
            },
            select: {
                id: true,
                timeStart: true,
                dateStart: true,
                timeEnd: true,
                createdAt: true,
                DivisionCalendar: {
                    select: {
                        id: true,
                        title: true,
                        desc: true,
                        linkMeet: true,
                        repeatEventTyper: true,
                        repeatValue: true,
                    }
                }
            }
        });


        if (kategori == "data") {
            const { DivisionCalendar, ...dataCalender } = data
            const timeStart = moment.utc(dataCalender?.timeStart).format("HH:mm")
            const timeEnd = moment.utc(dataCalender?.timeEnd).format("HH:mm")
            const dateStart = moment.utc(dataCalender?.dateStart).format("LL")
            const dateStartFormat = moment.utc(dataCalender?.dateStart).format("DD-MM-YYYY")
            const idCalendar = data?.DivisionCalendar.id
            const title = data?.DivisionCalendar?.title
            const desc = data?.DivisionCalendar?.desc
            const linkMeet = data?.DivisionCalendar?.linkMeet
            const repeatEventTyper = data?.DivisionCalendar?.repeatEventTyper
            const repeatValue = data?.DivisionCalendar?.repeatValue


            dataFix = { ...dataCalender, timeStart, timeEnd, dateStart, dateStartFormat, idCalendar, title, desc, linkMeet, repeatEventTyper, repeatValue }
        } else if (kategori == "member") {
            const member = await prisma.divisionCalendarMember.findMany({
                where: {
                    idCalendar: data?.DivisionCalendar.id
                },
                select: {
                    id: true,
                    idUser: true,
                    User: {
                        select: {
                            id: true,
                            name: true,
                            email: true,
                            img: true
                        }
                    }
                }
            })

            dataFix = member.map((v: any) => ({
                ..._.omit(v, ["User"]),
                name: v.User.name,
                email: v.User.email,
                img: v.User.img
            }))

        }


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

    } catch (error) {
        return NextResponse.json({ success: false, message: "Gagal mendapatkan kalender, data tidak ditemukan (error: 500)", }, { status: 500 });
    }
}

// DELETE CALENDER BY ID
export async function DELETE(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params
        const { user } = (await request.json())

        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 });
        }

        const cek = await prisma.divisionCalendar.count({
            where: {
                id: id
            }
        })

        if (cek == 0) {
            return NextResponse.json(
                {
                    success: false,
                    message: "Gagal menghapus acara kalender, data tidak ditemukan",
                },
                { status: 200 }
            );
        }

        const data = await prisma.divisionCalendar.update({
            where: {
                id: id
            },
            data: {
                isActive: false
            },
            select: {
                dateStart: true
            }
        });

        // create log user
        const log = await createLogUserMobile({ act: 'DELETE', desc: 'User menghapus data acara kalender', table: 'divisionCalendar', data: id, user: userMobile.id })

        return NextResponse.json({ success: true, message: "Berhasil menghapus acara kalender", data, user: user.id }, { status: 200 });

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

// EDIT CALENDER BY IDKALENDER
export async function PUT(request: Request, context: { params: { id: string } }) {
    try {

        const { id } = context.params
        const { title, desc, timeStart, dateStart, timeEnd, linkMeet, repeatEventTyper, repeatValue, user } = await request.json()

        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 });
        }

        const userId = userMobile.id

        const cek = await prisma.divisionCalendar.count({
            where: {
                id: id
            }
        })

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

        const dateStartFix = moment(dateStart, 'DD-MM-YYYY').format('YYYY-MM-DD')
        const y = new Date('1970-01-01 ' + timeStart)
        const x = new Date('1970-01-01 ' + timeEnd)
        const timeStartFix = new Date(y.getTime() - (y.getTimezoneOffset() * 60000)).toISOString()
        const timeEndFix = new Date(x.getTime() - (x.getTimezoneOffset() * 60000)).toISOString()
        const statusCalender = 0
        const data = await prisma.divisionCalendar.update({
            where: {
                id: id
            },
            data: {
                title: title,
                desc: desc,
                createdBy: String(userId),
                timeStart: timeStartFix,
                dateStart: new Date(dateStartFix),
                timeEnd: timeEndFix,
                linkMeet: linkMeet,
                repeatEventTyper: repeatEventTyper,
                status: statusCalender,
                repeatValue: Number(repeatValue)
            },
            select: {
                idDivision: true
            }
        });

        const freq: Frequency = repeatEventTyper === "yearly" ? RRule.YEARLY :
            repeatEventTyper === "monthly" ? RRule.MONTHLY :
                repeatEventTyper === "weekly" ? RRule.WEEKLY :
                    repeatEventTyper === "daily" ? RRule.DAILY :
                        repeatEventTyper === "hourly" ? RRule.HOURLY :
                            repeatEventTyper === "minutely" ? RRule.MINUTELY :
                                RRule.SECONDLY;

        const rule = new RRule({
            freq,
            interval: 1,
            dtstart: new Date(dateStartFix),
            count: repeatValue
        });

        const hasil = rule.all().map(recurrenceDate => ({
            idDivision: data.idDivision,
            idCalendar: id,
            dateStart: recurrenceDate,
            timeStart: timeStartFix,
            timeEnd: timeEndFix,
            dateEnd: recurrenceDate
        }));

        const deleteReminder = await prisma.divisionCalendarReminder.deleteMany({
            where: {
                idCalendar: id
            }
        })

        const insertReminder = await prisma.divisionCalendarReminder.createMany({
            data: hasil
        })


        // create log user
        const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengupdate data acara kalender', table: 'divisionCalendar', data: id, user: userMobile.id })

        return NextResponse.json({ success: true, message: "Berhasil mengedit acara" }, { status: 200 });

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