import { Request, Response, NextFunction } from 'express';
import { UserServices } from '../services/user.mjs';

export function auth(userServices: UserServices, unlessPath: string[]) {
    return async (req: Request, res: Response, next: NextFunction) => {
        if (req.method === 'OPTIONS' || unlessPath.includes(req.path)) {
            return next();
        }

        const token = req.headers.authorization;
        if (!token) {
            console.error('Not login');
            return res.status(401).json({ error: 'Not Login' });
        }

        try {
            const user = await userServices.verifyToken(token);
            if (!user) {
                return res.status(401).json({ error: 'User Not Exist!' });
            }
    
            (req as IReqEx).user = user as any;
            next();
        } catch (error) {
            console.error('Verify user token failed', error);
            return res.status(500).json({ error: 'Verify user token failed' });
        }
    }
}

export interface IReqEx extends Request {
    user: { id: string, username: string };
}