// 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.get('/forex/:from/:to', async (req, res) => {
  try {
    console.log(req.params);
    if (!!req.params.from && !!req.params.to) {
      const result = db.query(
        'SELECT `from`,`to`,`rate` FROM forex where `to`=? and `from`=?  order by forex_date limit 1',
        [req.params.to, req.params.from],
        function (error, results) {
          res.json({ forex: results[0] });

          return res.status(400);
        },
      );
    }
  } catch (error) {
    logger.error('Error fetching forex', error);
    res.status(500).send('Server Error');
  }
});
router.get('/forex/', async (req, res) => {
  try {
    console.log(req.params);
    const result = db.query(
      'SELECT * FROM forex WHERE (forex.forex_date, forex.forex_id) IN ( SELECT MAX(forex_date), MAX(forex_id) FROM forex GROUP BY `from`, `to` ) ORDER BY forex_date DESC;',
      function (error, results) {
        if (error) return res.status(500);
        return res.status(200).json({ forex: results });
      },
    );
  } catch (error) {
    logger.error('Error fetching forex', error);
    res.status(500).send('Server Error');
  }
});
router.post('/forex/', async (req, res) => {
  try {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];
    console.log(req.body);
    if (!token) {
      return res.status(401).json({ error: 'Unauthorized' });
    }
    const decoded = jwt.verify(token, 'secretkey123');

    const result = db.query(
      'SELECT * FROM office WHERE LOWER(email) = ? and id = ? ',
      [decoded.email.toLowerCase(), decoded.id],
      function (error, results, fields) {
        if (error) throw error;
        if (!results.length)
          return res.json({
            message: 'we failed to authorize you',
            code: 401,
          });
        const user = results[0]; // This will store the first row that matches the query in the variable user
        console.log(req.body);
        if (results) {
          const query = 'INSERT INTO forex (`from`, `to`, rate) VALUES ?';

          db.query(
            query,
            [req.body.map((item) => [item.from, item.to, item.rate])],
            (err, results, fields) => {
              if (err) {
                return res.status(400).json({
                  message: 'Something went wrong,try again Bad Request',
                });
              } else {
                return res.status(200).json({
                  message: 'Data inserted successfully ',
                });
              }
            },
          );
        }
      },
    );
  } catch (error) {
    logger.error('Error fetching transaction', error);
    res.status(500).send('Server Error');
  }
});
module.exports = router;
