const Jwt = require('jsonwebtoken')
const db =  require('../utils/db.js')

const studentAuthMiddelware = async(req, res, next)=>{
    const token = req.header('Authorization')
    if(!token) return res.status(400).json({message:'Cannot get Token, unAuthorized HTTP.'})
    // verify token

    try {
        const isVerified = await Jwt.verify(token, process.env.JWT_SECRET_STUDENT)
        if(isVerified){
              // get data
              const userid = isVerified.studentid;
              const name = isVerified.name;
              const phone = isVerified.phone;
              // query to get
                const sql = `SELECT class, section, department FROM students WHERE id = ?`;
                db.query(sql, [userid], (err, result)=>{
                    if(err) return res.status(400).json({message:err})
                    if(result.length===0) return res.status(400).json({message:'Invalid request!'})
                    const selected = result[0]
                    // send info
                    req.token = token;
                    req.userid = userid;
                    req.classid = selected.class
                    req.sectionid = selected.section
                    req.departmentid = selected.department
                    req.name = name;
                    req.phone = phone;
                    next();  
                })
        }else{
            console.log(token)
            res.status(401).json({message: 'Invalid token'});
        }
    } catch (error) {
        console.log(token)
        res.status(402).json({message: 'Unauthorized token!'});
    }
}

module.exports = studentAuthMiddelware