import { prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { createLogUserMobile } from "@/module/user";
import _ from "lodash";
import { NextResponse } from "next/server";
import { sendFCMNotificationMany } from "../../../../../../../xsendMany";

// CREATE COMENT
export async function POST(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params
        const { comment, 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: "User tidak ditemukan" }, { status: 200 });
        }

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

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

        const data = await prisma.divisionDisscussionComment.create({
            data: {
                comment: comment,
                idDisscussion: id,
                createdBy: userMobile.id
            },
            select: {
                id: true,
            }
        })

        const dataDivision = await prisma.divisionDisscussion.findUnique({
            where: {
                id: id
            },
            select: {
                idDivision: true,
                createdBy: true,
                User: {
                    select: {
                        Subscribe: {
                            select: {
                                subscription: true
                            }
                        },
                        TokenDeviceUser: {
                            select: {
                                token: true
                            }
                        }
                    }
                }
            }
        })

        const member = await prisma.divisionMember.findMany({
            where: {
                idDivision: dataDivision?.idDivision
            },
            select: {
                idUser: true,
                User: {
                    select: {
                        Subscribe: {
                            select: {
                                subscription: true
                            }
                        },
                        TokenDeviceUser: {
                            select: {
                                token: true
                            }
                        }
                    }
                }
            }
        })

        const userSent = await prisma.user.findFirst({
            where: {
                id: userMobile.id
            },
            select: {
                name: true,
                img: true
            }
        })

        const memberFilter = [...member, { idUser: dataDivision?.createdBy, User: dataDivision?.User }].filter((v: any) => v.idUser != userMobile.id)
            .filter((v: any, index: number, self: any[]) =>
                index === self.findIndex((t) => t.idUser === v.idUser)
            );

        const dataFCM = memberFilter.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();
        if (userMobile.idUserRole != "supadmin") {
            const perbekel = await prisma.user.findFirst({
                where: {
                    isActive: true,
                    idUserRole: "supadmin",
                    idVillage: userMobile.idVillage
                },
                select: {
                    id: true,
                    Subscribe: {
                        select: {
                            subscription: true
                        }
                    },
                    TokenDeviceUser: {
                        select: {
                            token: true
                        }
                    }
                }
            })

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

        const commentNotif = comment.length > 300 ? comment.substring(0, 300) + '...' : comment;

        const tokenUnique = [...new Set(tokenDup.flat())].filter((v: any) => v != undefined && v != null && v != "");
        await sendFCMNotificationMany({
            token: tokenUnique,
            title: "Komentar Baru",
            body: `${userSent?.name}: ${commentNotif}`,
            data: { id: data.id, category: `division/${dataDivision?.idDivision}/discussion`, content: id }
        })

        // create log user
        const log = await createLogUserMobile({ act: 'CREATE', desc: 'User menambah komentar pada diskusi', table: 'divisionDisscussionComment', data: data.id, user: userMobile.id })

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

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

// EDIT KOMENTAR
export async function PUT(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params
        const { comment, 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: "User tidak ditemukan" }, { status: 200 });
        }

        const cek = await prisma.divisionDisscussionComment.count({
            where: {
                id,
                isActive: true
            }
        })

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

        const data = await prisma.divisionDisscussionComment.update({
            where: {
                id: id
            },
            data: {
                comment: comment,
                isEdited: true
            }
        })

        // create log user
        const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengedit komentar pada diskusi divisi', table: 'divisionDisscussionComment', data: id, user: userMobile.id })

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

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

// HAPUS KOMENTAR
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: "User tidak ditemukan" }, { status: 200 });
        }

        const cek = await prisma.divisionDisscussionComment.count({
            where: {
                id,
                isActive: true
            }
        })

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

        const data = await prisma.divisionDisscussionComment.update({
            where: {
                id: id
            },
            data: {
                isActive: false
            }
        })

        // create log user
        const log = await createLogUserMobile({ act: 'DELETE', desc: 'User menghapus komentar pada diskusi divisi', table: 'divisionDisscussionComment', data: id, user: userMobile.id })

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

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