import { DIR, funUploadFile, prisma } from "@/module/_global";
import { funGetUserById } from "@/module/auth";
import { createLogUserMobile } from "@/module/user";
import _ from "lodash";
import { NextResponse } from "next/server";


// GET ONE PENGUMUMAN, UNTUK TAMPIL DETAIL PENGUMUMAN
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 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 data = await prisma.announcement.count({
            where: {
                id: id,
                isActive: true,
            },
        });

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

        const announcement = await prisma.announcement.findUnique({
            where: {
                id: id,
            },
            select: {
                id: true,
                title: true,
                desc: true,
            },
        });

        const announcementMember = await prisma.announcementMember.findMany({
            where: {
                idAnnouncement: id,
            },
            select: {
                idGroup: true,
                idDivision: true,
                Group: {
                    select: {
                        name: true,
                    },
                },
                Division: {
                    select: {
                        name: true,
                    },
                },
            },
        });

        const formatMember = announcementMember.map((v: any) => ({
            ..._.omit(v, ["Group", "Division"]),
            idGroup: v.idGroup,
            idDivision: v.idDivision,
            group: v.Group.name,
            division: v.Division.name
        }))

        // const fixMember = Object.groupBy(formatMember, ({ group }) => group);
        const fixMember = _.groupBy(formatMember, ({ group }) => group);

        const file = await prisma.announcementFile.findMany({
            where: {
                idAnnouncement: id
            },
            select: {
                id: true,
                idStorage: true,
                name: true,
                extension: true
            }
        })


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



// HAPUS PENGUMUMAN
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 data = await prisma.announcement.count({
            where: {
                id: id,
            },
        });

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

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

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

        return NextResponse.json(
            {
                success: true,
                message: "Pengumuman berhasil dihapus",
            },
            { 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 });
    }
}



//  EDIT PENGUMUMAN
export async function PUT(request: Request, context: { params: { id: string } }) {
    try {
        const contentType = request.headers.get("content-type");
        let title, desc, groups, user, oldFile: any[] = [], 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, oldFile } = JSON.parse(dataBody as string))
        } else {
            ({ title, desc, groups, user } = await request.json());
        }


        const { id } = context.params;
        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 data = await prisma.announcement.count({
            where: {
                id: id,
            },
        });

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

        const update = await prisma.announcement.update({
            where: {
                id: id
            },
            data: {
                title,
                desc,
            },
        });

        // hapus semua member divisi pengumuman
        const hapus = await prisma.announcementMember.deleteMany({
            where: {
                idAnnouncement: id
            }
        })

        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: id,
                    idGroup: groups[i].id,
                    idDivision: element.id
                }
                memberDivision.push(fix)
            }
        }

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

        if (oldFile.length > 0) {
            for (let index = 0; index < oldFile.length; index++) {
                const element = oldFile[index];
                if (element.delete) {
                    await prisma.announcementFile.delete({
                        where: {
                            id: element.id
                        }
                    })
                }
            }
        }

        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: id,
                                name: fName,
                                extension: String(fExt)
                            }
                        })
                    }
                }
            }
        }

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

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

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

