require('dotenv').config();
const express = require('express');
const app = express();
const crypto = require('crypto');
const jwt = require('jsonwebtoken');
const db = require('./db');
const port = process.env.PORT || 8000

// Middleware to parse JSON bodies
app.use(express.json());

// Get token function
app.post('/gettoken', async (req, res) => {
  try {
    const { userid } = req.body;

    // Check if user id exists in database
    const query = 'SELECT * FROM members WHERE id = ?';
    db.query(query, [userid], async (err, results) => {
      if (err) {
        const response = {
          user: null,
          token: null,
          message: 'Internal Server Error',
          success: false,
          errorCode: 500
        };

        res.status(500).json(response);
      } else if (results.length === 0) {
        const response = {
          user: null,
          token: null,
          message: 'Invalid user id',
          success: false,
          errorCode: 401
        };
        res.status(401).json(response);
      } else {

        // Generate a JWT token
        const token = jwt.sign({ userId: userid }, process.env.SECRETKEY, { expiresIn: '1h' });
        const response= {user:{id:userid}, tokenTkn:token, message:'Token generated successfully.', success:true, errorCode:null};
        res.json( response );
      }
    });

  } catch (error) {
    //console.error(error);
    const response = {
      user: null,
      token: null,
      message: 'Internal Server Error',
      success: false,
      errorCode: 500
    };
    res.status(500).json(response);
  }
});


////////////////////////////////////////////////////////////////////////////////////////////////////////

function hashPasswordWithSalt(password, salt) {
  const hash = crypto.createHash('sha256');
  hash.update((password + salt).toString());
  return { hash: hash.digest('hex') };
}

// Login endpoint
app.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;

    // Query the database for the user
    const query = 'SELECT * FROM members WHERE username = ?';
    db.query(query, [username], async (err, results) => {
      if (err) {
        //console.error(err);
        const response = {
          user: null,
          token: null,
          message: 'Internal Server Error',
          success: false,
          errorCode: 500
        };

        res.status(500).json(response);
      } else if (results.length === 0) {
        const response = {
          user: null,
          token: null,
          message: 'Invalid username or password',
          success: false,
          errorCode: 401
        };
        res.status(401).json(response);
      } else {
        const user = results[0];

        // Compare the provided password with the stored hash
        const hashedInput = hashPasswordWithSalt(password, user.salt);
        let isValidPassword = false;
        if(hashedInput.hash === user.password){
             isValidPassword=true;
        }
            
        if (!isValidPassword) {
          const response = {
            user: null,
            token: null,
            message: 'Invalid username or password',
            success: false,
            errorCode: 401
          };
          res.status(401).json(response);
        } else {
          // Generate a JWT token
          const token = jwt.sign({ userId: user.id }, process.env.SECRETKEY, { expiresIn: '1h' });

          //const response= {user:[{id:1,name:'manish'}], token:[{tokenTkn:token}] , error:[{errorCode:'Success', errormessage:'Data fetched successfully.'}]};
          const response= {user:{id:user.id, firstname:user.firstname, middlename:user.middlename, lastname:user.lastname, username:user.username }, tokenTkn:token, message:'User logged in successfully111111111.', success:true, errorCode:null};

          res.json( response );
        }
      }
    });
  } catch (error) {
    //console.error(error);
    const response = {
      user: null,
      token: null,
      message: 'Internal Server Error',
      success: false,
      errorCode: 500
    };
    res.status(500).json(response);
  }
});

  

// Protected endpoint
app.get('/protected', authenticateToken, (req, res) => {
  res.json({ message: 'Hello, authenticated user!' });
});
  

// Middleware to authenticate token
function authenticateToken(req, res, next) {
  const token = req.header('Authorization');
  
  if (!token) {
    res.status(401).json({ message: 'Access denied. No token provided.' });
  } else {
    jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
    if (err) {
        res.status(400).json({ message: 'Invalid token' });
    } else {
        req.user = decoded;
        next();
    }
    });
  }
}  
 
app.get('/', function (req, res) {
  res.send('Authorization Error.')
})

// Start the server
app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});