// In the Node.js server, in the routes/users.js file
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');
router.post('/user/create', async (req, res) => {
  //   console.log(req.body);
  const { fullname, email, mobile, password, terms, document } = req.body;

  if (!fullname || !email || !mobile || !password) {
    return res.status(400).send({
      message: 'Please fill in all required fields',
      fullname,
      email,
      mobile,
      password,
    });
  }
  const { front, back, type } = document;

  try {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    const result = db.query(
      'SELECT * FROM users WHERE LOWER(email) = ?',
      [email.toLowerCase()],
      async function (error, results, fields) {
        console.log(results.values);
        if (error)
          res.status(500).json({ message: ' Oops something went wrong' });
        if (!!results.length) {
          return res.status(400).json({ message: 'User already exists' });
        }
        const newUser = {
          fullname,
          email,
          mobile,
          password: hashedPassword,
          front,
          back,
          type,
        };

        const insertId = db.query(
          'INSERT INTO users SET ?',
          newUser,
          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' });
            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;
