const jwt = require('jsonwebtoken');

// Admin Authentication middleware for mock tokens
const authenticateAdmin = async (req, res, next) => {
    try {
        const authHeader = req.headers['authorization'];
        const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
        
        if (!token) {
            return res.status(401).json({
                success: false,
                message: 'Access token required'
            });
        }
        
        // Check if it's a mock admin token
        if (token.startsWith('mock-jwt-token-')) {
            // Mock admin authentication - accept the token
            req.user = {
                id: 'admin-001',
                email: 'reconnectifly.rif@gmail.com',
                name: 'Admin User',
                role: 'Super Admin',
                isAdmin: true
            };
            req.admin = req.user; // Also set req.admin for compatibility
            return next();
        }
        
        // If it's not a mock token, try regular JWT verification
        const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key');
        
        // For regular users, check if they exist in database
        const User = require('../models/User');
        const user = await User.findById(decoded.id).select('-password');
        
        if (!user) {
            return res.status(401).json({
                success: false,
                message: 'Invalid token - user not found'
            });
        }
        
        req.user = user;
        req.admin = user; // Also set req.admin for compatibility
        next();
        
    } catch (error) {
        if (error.name === 'JsonWebTokenError') {
            return res.status(401).json({
                success: false,
                message: 'Invalid token'
            });
        }
        
        if (error.name === 'TokenExpiredError') {
            return res.status(401).json({
                success: false,
                message: 'Token expired'
            });
        }
        
        console.error('Admin auth middleware error:', error);
        return res.status(500).json({
            success: false,
            message: 'Authentication failed'
        });
    }
};

// Alias for compatibility with existing routes
const authenticateAdminToken = authenticateAdmin;

// Role-based access control for admin
const requireRole = (roles) => {
    return (req, res, next) => {
        if (!req.admin) {
            return res.status(401).json({
                success: false,
                message: 'Authentication required'
            });
        }
        
        const userRole = req.admin.role || 'user';
        
        if (!roles.includes(userRole)) {
            return res.status(403).json({
                success: false,
                message: 'Insufficient permissions'
            });
        }
        
        next();
    };
};

module.exports = {
    authenticateAdmin,
    authenticateAdminToken,
    requireRole
};