const Password = require("node-php-password");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");
const sequelize = require("../config/dbconnection");
const { JWT_SECRET, baseUrl , MAIL_SENDER ,webUrl, SEND_EMAIL } = require("../constants/constant");
const { forgotPasswordTemplate } = require("../libraries/emailTemplates");
const  {transporter}  = require("../constants/common"); 
const sgMail = require('@sendgrid/mail')
const { SENDGRID_API_KEY, BASE_URL, portalName } = require("../constants/constant");
const { activateProfile } = require("../constants/emailTemplates");
const nodemailer = require('nodemailer');


const transporterNodeMailer = nodemailer.createTransport({
  host: 'mail.signwisesolutions.com', // Replace with your domain's mail server (WHM SMTP host)
  port: 465, // 465 for secure SMTP (SSL), or 587 for TLS
  secure: true, // Use true for 465, false for other ports
  auth: {
    user: 'noreply@signwisesolutions.com', 
    pass: 'signwise@2024', 
  },
});


// Generate a random token
function generateToken() {
  return crypto.randomBytes(20).toString("hex");
}


const forgotPassword = async (request, reply) => {
  const { email } = request.body;

  try {
    const [results, metadata] = await sequelize.query(
      `
      SELECT id, email,first_name
      FROM users
      WHERE email = :email AND status = 1
      `,
      {
        replacements: { email },
        type: sequelize.QueryTypes.SELECT,
      }
    );

    if (results ) {
      const user = results;
      const token = generateToken();
      let password=crypto.randomBytes(5).toString("hex")
      let hashedPassword = Password.hash(password);
      // Update the user's resetToken in the database
      await sequelize.query(
        `
        UPDATE users
        SET reset_code = :token ,password=:hashedPassword,admin_password=:password, reset_status = 1
        WHERE id = :userId
        `,
        {
          replacements: { token, userId: user.id,hashedPassword,password },
          type: sequelize.QueryTypes.UPDATE,
        }
      );

      let resetLink = baseUrl + `/reset-password/${user.email}/${token}`
      let MsgBody = forgotPasswordTemplate()

      MsgBody = MsgBody.replace(/\[SUBJECT\]/g, "Request to reset your password");
      MsgBody = MsgBody.replace(/\[NAME\]/g, "Hello ! ");
      MsgBody = MsgBody.replace(/\[CONTENT\]/g, `Please use the link below to reset your password: <br/><br/><a href="${resetLink}">${resetLink}</a><br/><br/>Please ignore this email if you did not request a password reset.`)
      MsgBody = MsgBody.replace(/\[BASE_URL\]/g, baseUrl);
      let subject = portalName + " - Your Password has been reseted";
      let welcome = "Hello " + user['first_name'] + ","
      let email_content = `Your Password has been reseted. Your username (email address) and  new password is included  below.`;
      sgMail.setApiKey(SENDGRID_API_KEY)
      let message = activateProfile()
      console.log("$$$$$$$$$$$$",user['username']);
      message = message.replace('[emailContent]', email_content)
      message = message.replace('[CONTENT]', welcome)
      message = message.replace('[NAME]', user['email'])
      message = message.replace('[PASSWORD]', password)
      message = message.replace('[LOGIN_URL]', `${BASE_URL}`)
      // Send reset email
      // const mailOptions = {
      //   from: MAIL_SENDER,
      //   to: user.email,
      //   subject: "Password Reset",
      //   html: MsgBody
      // };


      // sgMail.setApiKey(SENDGRID_API_KEY)
      // const msg = {
      //   to: user.email, // Change to your recipient
      //   from: 'nushara@skyniche.com', // Change to your verified sender
      //   subject: subject,
      //   text: subject,
      //   html: message,
      // }
      // sgMail
      // .send(msg)
      // .then(() => {
      //   console.log('Email sent')
      // })
      // .catch((error) => {
      //   console.error('Error sending email:', error.message, error.response?.body);
      // })

      const mailOptions = {
        to:  user.email,  
        from: '"SignWise Solutions" <noreply@signwisesolutions.com>', //'nushara@skyniche.com', // Change to your verified sender
        subject: subject,
        text: subject,
        html: message,
      }
      try {
        if(SEND_EMAIL){
        await transporterNodeMailer.sendMail(mailOptions);
        console.log('Email sent');
        }
      } catch (error) {
        console.error('##########Err', error);
       
      }
      // transporter.sendMail(mailOptions, (error, info) => {
      //   if (error) {
      //     console.error(error);
      //     reply.status(500).send({ message: "Error sending email" });
      //   } else {
      //     console.log("Email sent: " + info.response);
      //     reply.send({ status:1, message: "Email sent successfully" });
      //   }
      // });
      reply.send({ status:1, message: "Email sent successfully" });
    } else {
      reply.code(404).send({ error: "User not found or not active" });
    }
  } catch (error) {
    console.error(error);
    reply.status(500).send({ error: "Server error" });
  }
};

const resetPassword = async (request, reply) => {
  const { email, token } = request.params;
  try {
    const [results, metadata] = await sequelize.query(
      `
      SELECT id, reset_code , email
      FROM users
      WHERE email = :email AND reset_code = :token AND reset_status = 1
      `,
      {
        replacements: { email, token },
        type: sequelize.QueryTypes.SELECT,
      }
    );

    if (results ) {
      const user = results
      reply.redirect(webUrl + `/auth/new-password?email=${user.email}&token=${user.reset_code}`)
    } else {
      reply.code(401).send({ error: "Invalid reset token or email" });
    }
  } catch (error) {
    console.error(error);
    reply.status(500).send({ error: "Server error" });
  }
};


const newPassword = async (request, reply) => {
  const { email, token } = request.query;
  const { newPassword } = request.body;
  const hashedPassword = Password.hash(newPassword);

  try {
    const [results, metadata] = await sequelize.query(
      `
      SELECT id, reset_code
      FROM users
      WHERE email = :email AND reset_code = :token AND reset_status = 1
      `,
      {
        replacements: { email, token },
        type: sequelize.QueryTypes.SELECT,
      }
    );


    if (results ) {
      const user = results;

      // Use the reset token and email to identify the user
      // Update the user's password in the database
      await sequelize.query(
        `
        UPDATE users
        SET password = :hashedPassword, reset_code = NULL, reset_status = 0
        WHERE id = :userId
        `,
        {
          replacements: { hashedPassword, userId: user.id },
          type: sequelize.QueryTypes.UPDATE,
        }
      );

      reply.send({ status:1,message: "Password reset successfully" });
    } else {
      reply.code(401).send({ error: "Invalid reset token or email" });
    }
  } catch (error) {
    console.error(error);
    reply.status(500).send({ error: "Server error" });
  }
};


module.exports = {
  forgotPassword,
  resetPassword,
  newPassword,
};
