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

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

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

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

    try {

        const authHeader =
            req.headers.authorization;

        if (

            !authHeader ||

            !authHeader.startsWith("Bearer ")

        ) {

            return res.status(401).json({

                success: false,

                message: "Authentication token is required."

            });

        }

        const token =

            authHeader.split(" ")[1];

        let payload;

        try {

            payload =

                Jwt.verify(token);

        }

        catch (error) {

            return res.status(401).json({

                success: false,

                message: "Invalid or expired token."

            });

        }

        const user =

            await AuthRepository.findById(

                payload.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) {

        console.error(error);

        return res.status(500).json({

            success: false,

            message: "Authentication failed."

        });

    }

};