const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const router = express.Router();
router.use(bodyParser.json());
const secretKey = 'secretkey123'; // A secret key used to sign the JWT
const { generateOTP } = require('../utils');
const db = require('../db');
const logger = require('../utils/logger');
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
  host: 'mail.kingkanhi.co.ke',
  port: 465,
  secure: true,
  auth: {
    user: 'noreply@kingkanhi.co.ke',
    pass: 'SatarNoreply@ewajibu2021',
  },
});

router.post('/forgot-password', async (req, res) => {
  console.log({ body: req.body });
  const { email } = req.body;

  // Check if the email exists in the database
  // const [rows] = await db.execute('SELECT * FROM tenants WHERE email = ?', [
  //   email,
  // ]);

  // if (rows.length === 0) {
  //   return res.status(404).json({ message: 'Email not found' });
  // }
  const result = db.query(
    'SELECT * FROM tenants WHERE LOWER(email) = ? ',
    [email.toLowerCase()],
    async function (error, results, fields) {
      if (error) throw error;
      if (!results.length)
        return res.status(404).json({ message: 'Email not found' });
      const user = results[0]; // This will store the first row that matches the query in the variable user

      // Generate a unique token (you may use a library like uuid)
      const resetToken = Math.round(Math.random() * 10000);

      // Save the token in the database
      await db.execute('UPDATE tenants SET reset_token = ? WHERE email = ?', [
        resetToken,
        email,
      ]);

      // Send the password reset email
      const mailOptions = {
        from: 'noreply@edaji.co.ke',
        to: email,
        subject: 'Password Reset',
        html: `
       
        <div style="font-family: Helvetica,Arial,sans-serif;min-width:1000px;overflow:auto;line-height:2">
  <div style="margin:50px auto;width:70%;padding:20px 0">
    <div style="border-bottom:1px solid #eee">
      <a href="" style="font-size:1.4em;color: #00466a;text-decoration:none;font-weight:600">King Kanhi Investments Limited</a>
    </div>
    <p style="font-size:1.1em">Hi,</p>
    <p>Thank you for choosing King Kanhi Investments Limited. Use the following OTP to complete your Sign Up procedures. OTP is valid for 5 minutes</p>
    <h2 style="background: #00466a;margin: 0 auto;width: max-content;padding: 0 10px;color: #fff;border-radius: 4px;">${resetToken}</h2>
    <p style="font-size:0.9em;">Regards,<br />King Kanhi Investments Limited</p>
    <hr style="border:none;border-top:1px solid #eee" />
    <div style="float:left;padding:8px 0;color:#aaa;font-size:0.8em;line-height:1;font-weight:300">
      <p>King Kanhi Investments Limited
      
      </p>
      <p>Kirinyaga Road, Nairobi Kenya.
      Hebatullah Buildings, 1st Floor
     
      </p>
      <p> Block F - Unit Number 5.</p>
      <p>+254 790 601 199</p>
      <p>info@kingkanhi.co.ke</p>
    </div>
  </div>
</div>
      `,
      };
      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          return res.status(500).json({ message: 'Error sending email' });
        }
        res.status(200).json({
          message: 'Password reset email sent successfully',
          status: 200,
          token: resetToken,
        });
      });
    },
  );
});

router.post('/reset-password', async (req, res) => {
  //   console.log(req.body);
  const { fullname, email, mobile, password, terms, document, token } =
    req.body;

  if (!email || !token || !password) {
    return res.status(400).send({
      message: 'Please fill in all required fields',
      email,
      token,
      password,
    });
  }
  if (!email || !token || !password) {
    return res.status(400).send({
      message: 'Please fill in all required fields',
      email,
      token,
      password,
    });
  }

  try {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    const result = db.query(
      'SELECT * FROM tenants WHERE LOWER(email) = ?  and reset_token=?',
      [email.toLowerCase(), +token],
      async function (error, results, fields) {
        console.log(results);
        if (error)
          res.status(500).json({ message: ' Oops something went wrong' });
        if (!results.length) {
          return res
            .status(400)
            .json({ message: 'token or email is incorrect' });
        }

        const insertId = db.query(
          'update tenants SET  password = ? where LOWER(email) = ? ',
          [hashedPassword, email.toLowerCase()],
          function (error, results) {
            if (error) {
              return res.status(500).json({
                message:
                  'Oops something went wrong, try again if you keep on getting this message, contact us',
              });
            }
            res.status(201).json({ message: 'success', status: 200 });
            logger.info('User created successfully');
          },
        );

        const otp = generateOTP();
        // const transporter = nodemailer.createTransport({
        //   service: 'Gmail',
        //   auth: {
        //     user: 'iamsatarmovic@gmail.com',
        //     pass: 'nadifa2038',
        //   },
        // });
        // const mailOptions = {
        //   from: 'iamsatarmovic@gmail.com',
        //   to: email,
        //   subject: 'OTP for account activation',
        //   text: `Your OTP for account activation is ${otp}.`,
        // };
        // await transporter.sendMail(mailOptions);
      },
    );
  } catch (error) {
    console.error(error);
    logger.error('Error creating user', error);
    res.status(500).send('Server Error');
  }
});

module.exports = router;

module.exports = router;
