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

interface AuthenticatedRequest extends Request {
    user?: JwtPayload | string;
}

export const tokenAuthenticator = async ( req: Request, res: Response, next: NextFunction): Promise<void> => {
    if (!req.headers.authorization)
    {
        res.status(401).json({ message: "Unauthorized"});
        return;
    }

    const token = req.headers.authorization?.split(" ")[1]; //pega o token do cabecalho da requisicao, undefined se nao achar

    if (!token)
    {
        res.status(401).json({ message: "Token Not Found"});
        return;
    }

    try{
        const decoded = jwt.verify(token, process.env["APP_SECRET"] as string) as JwtPayload;   //valida o token com app_secret, e atribui como jwtpayload
        const reqAuth = req as AuthenticatedRequest;
        reqAuth.user = decoded; //req recebe o jwtpayload da validacao
        next();
    } catch (error) {
        res.status(403).json({ message: "Invalid Token"});
    }
};