import { Request, Response, NextFunction } from "express";
import { JwtAdapter } from "../../config/jwt.js";

interface TokenPayload {
    id: number;
    email: string;
    role: string;
}

export interface AuthRequest extends Request {
    user?: TokenPayload;
}

export class AuthMiddleware {

    static validateJwt = (req: AuthRequest, res: Response, next: NextFunction) => {

        const authorization = req.header('Authorization');

        if (!authorization) {
            return res.status(401).json({
                error: 'No token provided'
            });
        }

        if (!authorization.startsWith('Bearer ')) {
            return res.status(401).json({
                error: 'Invalid Bearer token'
            });
        }

        const token = authorization.split(' ').at(1) ?? '';

        const payload = JwtAdapter.validateToken<TokenPayload>(token);

        if (!payload) {
            return res.status(401).json({
                error: 'Invalid token'
            });
        }

        req.user = payload;

        next();
    }
}