const jwt= require('jsonwebtoken')
const knex=require('../../database/knex.config')

async function authentication (req, res, next) {
  if (!req.headers.authorization) {
    return res.status(400).json({res: false, message: "unauthorized" });
  }
  const token = await req.headers.authorization.split(" ")[1];
  const decodedJwtToken =await jwt.decode(token);
  const user =await knex('users').where('phoneNumber',decodedJwtToken.phoneNumber).first()

  const accessToken=await knex('access_tokens').where('id',decodedJwtToken.jti).first()

  if (!user) {
    return res.status(400).json({
      res: false,
      message: "unauthorized",
    });
  }

  if(accessToken.revoked === 1){
    return res.status(400).json({
      res: false,
      message: "unauthorized",
    });
  }

  req.user = {
    id: user.id,
    email: user.email,
    phoneNumber: user.phoneNumber,
    jti: decodedJwtToken.jti
  };
  return next();

}

module.exports = authentication