import  { Request, Response, NextFunction } from "express";
import  jwt from "jsonwebtoken";

export const authMiddleware = (
    req:Request,
    res:Response,
    next:NextFunction
) => {

    const authHeader = req.headers.authorization;

    if(!authHeader){
        return res.status(401).json({
            message:"Token requerido"
        });
    }

    //Verificar formato Bearer

    if(!authHeader.startsWith("Bearer ")) {
        return res.status(401).json({
            message:"Formato de token inválido"
        });
    }
    const token = authHeader.split(" ")[1];

    if (!token)
    {
        return res.status(401).json({
            message:"Token inválido"
        });
    }

    try {

        const decoded = jwt.verify (
            token,
            process.env.JWT_SECRET as string,
        );

        (req as any).user = 
        decoded;

        next();
    } catch{
        return res.status(401).json({
            message:"Token inválido"
        });
    }
};