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


// GET PROFILE BY COOKIES
export async function GET(request: Request) {
    try {
        const user = await funGetUserByCookies()
        if (user.id == undefined) {
            return NextResponse.json({ success: false, message: "Anda harus login untuk mengakses ini" }, { status: 200 });
        }
        const data = await prisma.user.findUnique({
            where: {
                id: user.id
            },
            select: {
                id: true,
                idUserRole: true,
                name: true,
                email: true,
                phone: true,
                nik: true,
                gender: true,
                idGroup: true,
                idPosition: true,
                img: true,
                Group: {
                    select: {
                        name: true
                    }
                },
                Position: {
                    select: {
                        name: true
                    }
                },
                UserRole: {
                    select: {
                        name: true
                    }
                }
            }
        })
        const { ...userData } = data;
        const group = data?.Group.name
        const position = data?.Position?.name
        const phone = data?.phone.substr(2)
        const role = data?.UserRole.name

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

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

        return NextResponse.json({ success: true, data: result });
    } catch (error) {
        return NextResponse.json({ success: false, message: "Gagal mendapatkan data profile (error: 500)" }, { status: 500 });
    }

}

// UPDATE PROFILE BY COOKIES
export async function PUT(request: Request) {
    try {
        const body = await request.formData()
        const file = body.get("file") as File;
        const data = body.get("data");

        const { name, email, phone, nik, gender, idPosition, id } = JSON.parse(data as string)

        const user = await funGetUserById({ id: String(id) })
        if (user.id == "null" || user.id == undefined || user.id == "") {
            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: user.id
                }
            },
        });

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

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

        if (cekNIK > 0 || cekEmail > 0 || cekPhone > 0) {
            return NextResponse.json({ success: false, message: "Gagal ubah profile, NIK/email/phone sudah terdaftar" }, { status: 200 });
        }

        const update = await prisma.user.update({
            where: {
                id: user.id
            },
            data: {
                name: name,
                email: email,
                phone: "62" + phone,
                nik: nik,
                gender: gender,
                idPosition: idPosition
            },
            select: {
                img: true
            }
        })

        if (String(file) != "undefined" && String(file) != "null") {
            const fExt = file.name.split(".").pop()
            const fileName = user.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(update.img) })
            const upload = await funUploadFile({ file: resizedFile, dirId: DIR.user })
            if (upload.success) {
                await prisma.user.update({
                    where: {
                        id: user.id
                    },
                    data: {
                        img: upload.data.id
                    }
                })
            }

        }

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

        return NextResponse.json({ success: true, message: "Berhasil ubah profile" });
    } catch (error) {
        return NextResponse.json({ success: false, message: "Gagal mengubah profile (error: 500)" }, { status: 500 });
    }
}

