/**
 * ==========================================================
 * Smart Attendance System
 * JWT Authentication Middleware
 * ==========================================================
 */

const Jwt =
require("../utils/jwt");

const AuthRepository =
require("../repositories/auth.repository");

module.exports = async (req,res,next)=>{

    try{

        const authHeader =

            req.headers.authorization;

        if(

            !authHeader ||

            !authHeader.startsWith("Bearer ")

        ){

            return res.status(401).json({

                success:false,

                message:"Unauthorized."

            });

        }

        const token =

            authHeader.split(" ")[1];

        const decoded =

            Jwt.verify(token);

        const user =

            await AuthRepository.findById(

                decoded.id

            );

        if(!user){

            return res.status(401).json({

                success:false,

                message:"User not found."

            });

        }

        if(user.status!=="active"){

            return res.status(403).json({

                success:false,

                message:"User account is inactive."

            });

        }

        req.user = user;

        next();

    }

    catch(error){

        return res.status(401).json({

            success:false,

            message:"Invalid or expired token."

        });

    }

};