// In the Node.js server, in the routes/tenants.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 db = require('../db');
const logger = require('../utils/logger');
const getUseDetails = function (email, password) {
  return new Promise(function (resolve, reject) {
    db.query(
      'SELECT * FROM tenants WHERE email = ? AND password = ?',
      [email, password],
      function (err, rows) {
        if (rows === undefined) {
          reject(new Error('Error rows is undefined'));
        } else {
          resolve(rows);
        }
      },
    );
  });
};
router.post('/login', async (req, res) => {
  // Verify the user's credentials
  const email = req.body.email;
  const password = req.body.password;
  if (!!email && !!password) {
    // Create the JWT

    try {
      const result = db.query(
        'SELECT * FROM tenants WHERE LOWER(email) = ? ',
        [email.toLowerCase()],
        function (error, results, fields) {
          if (error)
            throw res.status(500).json({
              message: 'Server error! its us not you',
            });
          if (!results.length)
            return res.json({
              message: 'wrong email and password combination',
              code: 401,
            });
          const user = results[0]; // This will store the first row that matches the query in the variable user

          bcrypt.compare(password, user.password, function (err, outcome) {
            if (outcome) {
              const payload = user;
              const token = jwt.sign(payload, secretKey);

              // Send the JWT to the React Native app
              res.json({
                token,
                message: 'you have successfully logged in',
                code: 200,
              });
              logger.info('User successfully logged in');
            } else {
              // Passwords don't match
              res.status(403).json({ message: 'password  mismatch' });
              logger.info('User password dont mactch');
            }
          });
        },
      );
    } catch (error) {
      console.error(error);
      logger.error('Error creating user', error);
      res.status(500).send('Server Error');
    }
  } else {
    // Invalid credentials, send an error response
    console.log('here is the req payload', req.body);
    res.status(401).json({ error: 'Invalid credentials' });
  }
});
router.post('/login/office', async (req, res) => {
  // Verify the user's credentials
  const email = req.body.email;
  const password = req.body.password;
  if (!!email && !!password) {
    // Create the JWT

    try {
      const result = db.query(
        'SELECT * FROM office WHERE LOWER(email) = ? ',
        [email.toLowerCase()],
        function (error, results, fields) {
          if (error) throw error;
          if (!results.length)
            return res.json({
              message: 'wrong email and password combination',
              code: 401,
            });
          const user = results[0]; // This will store the first row that matches the query in the variable user

          bcrypt.compare(password, user.password, function (err, outcome) {
            if (outcome) {
              const payload = user;
              const token = jwt.sign(payload, secretKey);

              // Send the JWT to the React Native app
              res.json({
                token,
                message: 'you have successfully logged in',
                code: 200,
              });
              logger.info(' Office User successfully logged in');
            } else {
              // Passwords don't match
              res.status(403).json({ message: 'password  mismatch' });
              logger.info('User password dont mactch');
            }
          });
        },
      );
    } catch (error) {
      console.error(error);
      logger.error('Error creating user', error);
      res.status(500).send('Server Error');
    }
  } else {
    // Invalid credentials, send an error response
    console.log('here is the req payload', req.body);
    res.status(401).json({ error: 'Invalid credentials' });
  }
});

router.get('/protected-route', (req, res) => {
  // Extract the JWT from the request header
  const authHeader = req.headers.authorization;
  const token = authHeader && authHeader.split(' ')[1];

  // Verify the JWT
  jwt.verify(token, secretKey, (err, user) => {
    if (err) {
      // JWT is invalid, return an error response
      res.status(403).json({ error: 'Invalid JWT' });
    } else {
      // JWT is valid, return the protected data
      res.json({ data: 'Protected data' });
    }
  });
});

router.put('/user/:userId', (req, res) => {
  // Handle a PUT request to the /tenants/:userId route
});

router.delete('/user/:userId', (req, res) => {
  // Handle a DELETE request to the /tenants/:userId route
});

module.exports = router;
