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

// GET ONE MEMBER / USER 
export async function GET(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;

        const users = await prisma.user.findUnique({
            where: {
                id: id,
            },
            select: {
                id: true,
                nik: true,
                name: true,
                phone: true,
                email: true,
                gender: true,
                img: true,
                idGroup: true,
                isActive: true,
                isApprover: true,
                idPosition: true,
                UserRole: {
                    select: {
                        name: true,
                        id: true
                    }
                },
                Position: {
                    select: {
                        name: true,
                        id: true
                    },
                },
                Group: {
                    select: {
                        name: true,
                        id: true
                    },
                },
                Village:{
                    select:{
                        name:true,
                        isActive:true,
                    }
                }
            },
        });

        const { ...userData } = users;
        const group = users?.Group.name
        const position = users?.Position?.name
        const idUserRole = users?.UserRole.id
        const phone = users?.phone.substr(2)
        const role = users?.UserRole.name
        const village = users?.Village.name
        const villageIsActive = users?.Village.isActive

        const result = { ...userData, group, position, idUserRole, phone, role, village, villageIsActive };

        const omitData = _.omit(result, ["Group", "Position", "UserRole", "Village"]);



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

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


// DELETE / ACTIVE & NON ACTIVE MEMBER / USER
export async function DELETE(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;
        const { isActive, user } = (await request.json());

        if (user == "null" || user == undefined || user == "") {
            return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
        }

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

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

        const result = await prisma.user.update({
            where: {
                id: id,
            },
            data: {
                isActive: !isActive,
            },
            select: {
                id: true,
                idGroup: true,
            },
        });

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

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

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


// TOGGLE APPROVER STATUS
export async function PATCH(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;
        const { user, isApprover } = await request.json();

        if (user == "null" || user == undefined || user == "") {
            return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
        }

        const data = await prisma.user.count({ where: { id } });
        if (data == 0) {
            return NextResponse.json({ success: false, message: "Anggota tidak ditemukan" }, { status: 200 });
        }

        await prisma.user.update({
            where: { id },
            data: { isApprover: Boolean(isApprover) },
        });

        const log = await createLogUserMobile({ act: 'UPDATE', desc: 'User mengupdate status approver anggota', table: 'user', data: id, user });

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

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


// UPDATE MEMBER
export async function PUT(request: Request, context: { params: { id: string } }) {
    try {
        const { id } = context.params;

        const body = await request.formData()
        const file = body.get("file") as File
        const data = body.get("data")
        const {
            name,
            email,
            phone,
            nik,
            gender,
            idGroup,
            idPosition,
            idUserRole,
            user
        } = JSON.parse(data as string)

        if (user == "null" || user == undefined || user == "") {
            return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
        }

        const cekNIK = await prisma.user.count({
            where: {
                nik: nik,
                NOT: {
                    id: id
                }
            },
        });

        const cekEmail = await prisma.user.count({
            where: {
                email: email,
                NOT: {
                    id: id
                }
            },
        });

        const cekPhone = await prisma.user.count({
            where: {
                phone: "62" + phone,
                NOT: {
                    id: id
                }
            },
        });

        if (cekNIK == 0 && cekEmail == 0 && cekPhone == 0) {
            const updates = await prisma.user.update({
                where: {
                    id: id
                },
                data: {
                    nik: nik,
                    name: name,
                    phone: "62" + phone,
                    email: email,
                    gender: gender,
                    idGroup: idGroup,
                    idPosition: idPosition,
                    idUserRole: idUserRole,
                },
                select: {
                    img: true
                }
            });

            if (String(file) != "undefined" && String(file) != "null") {
                const fExt = file.name.split(".").pop()
                const fileName = id + '.' + fExt;

                // Resize ukuran
                const imageBuffer = await file.arrayBuffer();
                const resize = await sharp(imageBuffer).resize(300).toBuffer();

                // Convert buffer ke Blob
                const blob = new Blob([resize as any], { type: file.type });

                // Convert Blob ke File
                const resizedFile = new File([blob], fileName, {
                    type: file.type,
                    lastModified: new Date().getTime(),
                });

                // const newFile = new File([file], fileName, { type: file.type });

                await funDeleteFile({ fileId: String(updates.img) })
                const upload = await funUploadFile({ file: resizedFile, dirId: DIR.user })
                await prisma.user.update({
                    where: {
                        id: id
                    },
                    data: {
                        img: upload.data.id
                    }
                })
            }

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

            return Response.json(
                { success: true, message: "Sukses update anggota" },
                { status: 200 }
            );
        } else {
            return Response.json({ success: false, message: "Anggota sudah ada" }, { status: 200 });
        }
    } catch (error) {
        console.error(error);
        return NextResponse.json({ success: false, message: "Gagal mengupdate data anggota, coba lagi nanti (error: 500)", reason: (error as Error).message, }, { status: 500 });
    }
}