import { decryptUUID } from "@/utils/crypto/cryptography"
import { getLogger } from "@/utils/logger"
import { NextRequest, NextResponse } from "next/server"
import db from "@/lib/db"
import bcrypt from "bcrypt";


const logger = getLogger("/api/orders/[uuid]")


export const PUT = async (request: NextRequest, { params }: { params: { token: string } }) => {

    try {
        const req = await request.json()

        const newPassword1 = req.newPassword1
        const newPassword2 = req.newPassword2
        const token = params.token

        //console.log(newPassword1)
        //console.log(newPassword2)
        //console.log(token)

        if (newPassword1 != newPassword2) {
            return NextResponse.json({ message: "Passwords do not match!" }, { status: 403 })
        }

        if (!token) {
            return NextResponse.json({ message: "Token is empty" }, { status: 403 })
        }

        // Decrypt the token & Reset the password

        const uuid = decryptUUID(token)

        //console.log(uuid)

        const user = await db.user.findUnique({ where: { uuid: uuid } })

        if (!user) {
            return NextResponse.json({ message: "Invalid token" }, { status: 403 })
        }

        const salt = await bcrypt.genSalt(10);
        const hashPassword = await bcrypt.hash(newPassword1, salt);

        const updatedUser = await db.user.update({
            where: { uuid: uuid },
            data: {
                password: hashPassword
            }
        })

        return NextResponse.json({ message: "Password reset successfully" }, { status: 200 })
        
    } catch (error: any) {
        logger.error("Error occurred when sending mail", { token: params.token, error: error.config.data });

        return new NextResponse("Internal Server Error", { status: 500 });
    }

}