import { NextRequest, NextResponse } from "next/server";
import db from "@/lib/db";
import bcrypt from "bcrypt";
import { getLogger } from "@/utils/logger";
import { authOptions } from "@/app/api/auth/[...nextauth]/auth-options";
import { getServerSession } from "next-auth";


const logger = getLogger("api/user/resetPassword");

export const PUT = async (req: NextRequest) => {
  try {
    //!----------- Getting user profile-----------//
    const session = await getServerSession(authOptions)

    if (!session) {
      return NextResponse.json({ mssg: "You are not authorized !" }, { status: 403 })
    }


    const data = await req.formData();

    //*---------geting user data-------//
    const userInfo = await db.user.findUnique({
      where: { uuid: session.user.uuid },
      include: {
        profile: true,
      },
    });


    if (userInfo) {
      const salt = await bcrypt.genSalt(10);

      if (userInfo.password && userInfo.password != userInfo.profile?.full_name){ 

        // console.log(userInfo.password)
        // console.log(userInfo.profile?.full_name)

        const isPasswordMatch = await bcrypt.compare(data.get('currentPassword') as string, userInfo.password);

        if (!isPasswordMatch) {
          logger.warn("Current password does not match", { status: 400 });
          return new NextResponse("Current password does not match", { status: 400 });
        }

      }
      const hashPassword = await bcrypt.hash(data.get('newPassword') as string, salt);
      const updatedUserInfo = await db.user.update({
        where: {
          uuid: session.user.uuid,
        },
        data: {
          password: hashPassword,
        },
      });

      return NextResponse.json({ user: updatedUserInfo, message: "Successful" }, { status: 200 });
    } else {
      logger.warn("User not found", { status: 404, uuid: session.user.uuid });
      return new NextResponse("User not found", { status: 404 });
    }
  } catch (error: any) {
    logger.error("Error occurred when updating user password", { errorMsg: error.message, errorData: error.config.data });
    return new NextResponse("Internal Server Error", { status: 500 });
  }
};
