import { countTime, DIR, 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";

// GET ONE DISCUSSION BY ID
export async function GET(request: Request, context: { params: { id: string } }) {
    const { id } = context.params
    const { searchParams } = new URL(request.url);
    const user = searchParams.get("user");
    const cat = searchParams.get("cat");
    const userMobile = await funGetUserById({ id: String(user) })

    try {
        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.divisionDisscussion.count({
            where: {
                id: id
            }
        })

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

        if (cat == "comment") {
            const data = await prisma.divisionDisscussionComment.findMany({
                where: {
                    idDisscussion: id,
                    isActive: true
                },
                select: {
                    id: true,
                    comment: true,
                    createdAt: true,
                    updatedAt: true,
                    isEdited: true,
                    createdBy: true,
                    User: {
                        select: {
                            name: true,
                            img: true
                        }
                    }
                },
                orderBy: {
                    createdAt: "asc"
                }
            })

            const omitMember = data.map((v: any) => ({
                ..._.omit(v, ["User", "createdBy", "createdAt", "updatedAt"]),
                idUser: v.createdBy,
                username: v.User.name,
                img: v.User.img,
                createdAt: countTime(v.createdAt),
                updatedAt: moment(v.updatedAt).format("ll")
            }))

            return NextResponse.json({ success: true, message: "Berhasil mendapatkan komentar", data: omitMember }, { status: 200 });
        } else if (cat == "file") {
            const data = await prisma.divisionDiscussionFile.findMany({
                where: {
                    idDiscussion: id,
                    isActive: true
                },
                select: {
                    id: true,
                    idStorage: true,
                    name: true,
                    extension: true
                }
            })

            return NextResponse.json({ success: true, message: "Berhasil mendapatkan file", data: data }, { status: 200 });
        } else {
            const data = await prisma.divisionDisscussion.findUnique({
                where: {
                    id: id
                },
                select: {
                    isActive: true,
                    id: true,
                    title: true,
                    desc: true,
                    status: true,
                    createdAt: true,
                    createdBy: true,
                    User: {
                        select: {
                            name: true,
                            img: true
                        }
                    }
                }
            });

            const { ...userMember } = _.omit(data, ["User", "createdAt"])
            const username = data?.User.name
            const user_img = data?.User.img
            const createdAt = moment(data?.createdAt).format("ll")
            const isCreator = data?.createdBy == userMobile.id

            const result = { ...userMember, username, createdAt, user_img, isCreator }
            return NextResponse.json({ success: true, message: "Berhasil mendapatkan diskusi", data: result }, { status: 200 });
        }

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


// OPEN OR CLOSE DISCUSSION
export async function DELETE(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params
        const { status, 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 });
        }

        let newStatus;
        if (status === 1) {
            newStatus = 2;
        } else if (status === 2) {
            newStatus = 1;
        } else {
            return NextResponse.json({ success: false, message: "Invalid status" }, { status: 200 });
        }

        const data = await prisma.divisionDisscussion.count({
            where: {
                id: id
            },
        });

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

        const result = await prisma.divisionDisscussion.update({
            where: {
                id: id
            },
            data: {
                status: newStatus
            }
        });

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

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

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

// DELETE DISCUSSION
export async function PUT(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params
        const { active, 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.divisionDisscussion.count({
            where: {
                id: id
            },
        });

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


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

        // create log user
        if (active) {
            const log = await createLogUserMobile({ act: 'DELETE', desc: 'User mengaktifkan data diskusi', table: 'divisionDisscussion', data: id, user: userMobile.id })
            return NextResponse.json({ success: true, message: "Berhasil mengaktifkan diskusi", user: userMobile.id }, { status: 200 });
        } else {
            const log = await createLogUserMobile({ act: 'DELETE', desc: 'User mengarsipkan data diskusi', table: 'divisionDisscussion', data: id, user: userMobile.id })
            return NextResponse.json({ success: true, message: "Berhasil mengarsipkan diskusi", user: userMobile.id }, { status: 200 });
        }

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


// EDIT DISCUSSION
export async function POST(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params
        const contentType = request.headers.get("content-type");

        let title, desc, 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, user, oldFile } = JSON.parse(dataBody as string))
        } else {
            ({ title, desc, 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.divisionDisscussion.count({
            where: {
                id: id
            },
        });

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

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

        if (oldFile.length > 0) {
            for (let index = 0; index < oldFile.length; index++) {
                const element = oldFile[index];
                if (element.delete) {
                    await prisma.divisionDiscussionFile.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.discussionDivision })
                    if (upload.success) {
                        await prisma.divisionDiscussionFile.create({
                            data: {
                                idStorage: upload.data.id,
                                idDiscussion: id,
                                name: fName,
                                extension: String(fExt)
                            }
                        })
                    }
                }
            }
        }

        // create log user
        const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengupdate data diskusi', table: 'divisionDisscussion', data: id, user: userMobile.id })
        return NextResponse.json({ success: true, message: "Berhasil mengedit diskusi" }, { status: 200 });

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