import { DIR, funSendWebPush, funUploadFile, 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 { sendFCMNotificationMany } from "../../../../../xsendMany";
export const dynamic = 'force-dynamic'



// GET ALL PENGUMUMAN
export async function GET(request: Request) {
    try {
        const { searchParams } = new URL(request.url);
        const name = searchParams.get('search');
        const page = searchParams.get('page');
        const user = searchParams.get('user');
        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 villageId = userMobile.idVillage
        const roleUser = userMobile.idUserRole
        const groupId = userMobile.idGroup

        const dataSkip = Number(page) * 10 - 10;

        let kondisi: any = {
            idVillage: String(villageId),
            isActive: true,
            title: {
                contains: (name == undefined || name == null) ? "" : name,
                mode: "insensitive"
            }
        }

        if (roleUser != "supadmin" && roleUser != "developer") {
            if (roleUser == "cosupadmin" || roleUser == "admin") {
                kondisi = {
                    idVillage: String(villageId),
                    isActive: true,
                    title: {
                        contains: (name == undefined || name == null) ? "" : name,
                        mode: "insensitive"
                    },
                    AnnouncementMember: {
                        some: {
                            idGroup: String(groupId)
                        }
                    }

                }
            } else {
                kondisi = {
                    idVillage: String(villageId),
                    isActive: true,
                    title: {
                        contains: (name == undefined || name == null) ? "" : name,
                        mode: "insensitive"
                    },
                    AnnouncementMember: {
                        some: {
                            idGroup: String(groupId),
                            Division: {
                                DivisionMember: {
                                    some: {
                                        idUser: String(userMobile.id)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


        const announcements = await prisma.announcement.findMany({
            skip: dataSkip,
            take: 10,
            where: kondisi,
            select: {
                id: true,
                title: true,
                desc: true,
                createdAt: true,
            },
            orderBy: {
                createdAt: 'desc'
            }
        });

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


        return NextResponse.json({ success: true, message: "Berhasil mendapatkan pengumuman", data: allData, }, { 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 });
    }
}



// CREATE PENGUMUMAN
export async function POST(request: Request) {
    try {
        const contentType = request.headers.get("content-type");

        let title, desc, groups, user, cekFile, body: FormData | undefined
        if (contentType?.includes("multipart/form-data")) {
            body = await request.formData()
            const dataBody = body.get("data")
            cekFile = body.has("file0");
            ({ title, desc, groups, user } = JSON.parse(dataBody as string))
        } else {
            ({ title, desc, groups, 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 villaId = userMobile.idVillage
        const userId = userMobile.id
        const userRoleLogin = userMobile.idUserRole

        const data = await prisma.announcement.create({
            data: {
                title,
                desc,
                idVillage: String(villaId),
                createdBy: String(userId),
            },
            select: {
                id: true,
            }
        });

        let memberDivision = []

        for (var i = 0, l = groups.length; i < l; i++) {
            var obj = groups[i].Division;
            for (let index = 0; index < obj.length; index++) {
                const element = obj[index];
                const fix = {
                    idAnnouncement: data.id,
                    idGroup: groups[i].id,
                    idDivision: element.id
                }
                memberDivision.push(fix)
            }
        }


        if (cekFile && body) {
            body.delete("data")
            for (var pair of body.entries()) {
                if (String(pair[0]).substring(0, 4) == "file") {
                    const file = body.get(pair[0]) as File
                    const fExt = file.name.split(".").pop()
                    const fName = decodeURIComponent(file.name.replace("." + fExt, ""))
                    const upload = await funUploadFile({ file: file, dirId: DIR.announcement })
                    if (upload.success) {
                        await prisma.announcementFile.create({
                            data: {
                                idStorage: upload.data.id,
                                idAnnouncement: data.id,
                                name: fName,
                                extension: String(fExt)
                            }
                        })
                    }
                }
            }
        }

        const announcementMember = await prisma.announcementMember.createMany({
            data: memberDivision,
        });

        const memberNotif = await prisma.divisionMember.findMany({
            where: {
                Division: {
                    AnnouncementMember: {
                        some: {
                            idAnnouncement: data.id
                        }
                    }
                }
            },
            select: {
                idUser: true,
                User: {
                    select: {
                        Subscribe: {
                            select: {
                                subscription: true
                            }
                        },
                        TokenDeviceUser: {
                            select: {
                                token: true
                            }
                        }
                    }
                }
            }
        })


        // mengirim notifikasi
        // dataFCM untuk push notifikasi mobile
        // datanotif untuk realtime notifikasi
        // datapush untuk web push notifikasi ketika aplikasi tidak aktif
        const dataFCM = memberNotif.map((v: any) => ({
            ..._.omit(v, ["idUser", "User", "Subscribe", "TokenDeviceUser"]),
            tokens: v.User.TokenDeviceUser.map((v: any) => v.token)
        }))
        const tokenDup = dataFCM.filter((v: any) => v.tokens.length > 0).map((v: any) => v.tokens).flat();

        const dataNotif = memberNotif.map((v: any) => ({
            ..._.omit(v, ["idUser", "User", "Subscribe", "TokenDeviceUser"]),
            idUserTo: v.idUser,
            idUserFrom: userId,
            category: 'announcement',
            idContent: data.id,
            title: 'Pengumuman Baru',
            desc: title
        }))


        const dataPush = memberNotif.map((v: any) => ({
            ..._.omit(v, ["idUser", "User", "Subscribe", "TokenDeviceUser"]),
            idUser: v.idUser,
            subscription: v.User.Subscribe?.subscription,
        }))


        if (userRoleLogin != "supadmin") {
            const perbekel = await prisma.user.findFirst({
                where: {
                    isActive: true,
                    idUserRole: "supadmin",
                    idVillage: String(villaId)
                },
                select: {
                    id: true,
                    Subscribe: {
                        select: {
                            subscription: true
                        }
                    },
                    TokenDeviceUser: {
                        select: {
                            token: true
                        }
                    }
                }
            })

            tokenDup.push(perbekel?.TokenDeviceUser.map((v: any) => v.token).flat())

            dataNotif.push({
                idUserTo: perbekel?.id,
                idUserFrom: userId,
                category: 'announcement',
                idContent: data.id,
                title: 'Pengumuman Baru',
                desc: title
            })

            dataPush.push({
                idUser: perbekel?.id,
                subscription: perbekel?.Subscribe?.subscription
            })
        }


        const dataNotifFilter = dataNotif.filter((v: any) => v.idUserTo != undefined && v.idUserTo != null && v.idUserTo != "" && v.idUserTo != userId)
        const dataNotifFilterUnique = dataNotifFilter
            .filter((v: any, index: number, self: any[]) =>
                index === self.findIndex((t: any) => t.idUserTo == v.idUserTo)
            )

        const pushNotif = dataPush.filter((item) => item.subscription != undefined)

        const sendWebPush = await funSendWebPush({ sub: pushNotif, message: { title: 'Pengumuman Baru', body: title } })
        const insertNotif = await prisma.notifications.createMany({
            data: dataNotifFilterUnique
        })

        const tokenUnique = [...new Set(tokenDup.flat())].filter((v: any) => v != undefined && v != null && v != "");

        await sendFCMNotificationMany({
            token: tokenUnique,
            title: "Pengumuman Baru",
            body: title,
            data: { id: data.id, category: "announcement", content: data.id }
        })

        // create log user
        const log = await createLogUserMobile({ act: 'CREATE', desc: 'User membuat data pengumuman baru', table: 'announcement', data: data.id, user: userMobile.id })

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

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