const { supabaseAdmin } = require('../config/supabase');

// Middleware to verify token (Simplified - works with base64 tokens)
async function authenticateUser(req, res, next) {
    try {
        const authHeader = req.headers.authorization;

        if (!authHeader || !authHeader.startsWith('Bearer ')) {
            return res.status(401).json({ error: 'Missing or invalid authorization header' });
        }

        const token = authHeader.substring(7);

        // Decode the simple base64 token
        let decoded;
        try {
            decoded = JSON.parse(Buffer.from(token, 'base64').toString());
        } catch (e) {
            return res.status(401).json({ error: 'Invalid token format' });
        }

        // Verify the user still exists in database
        const { data: user, error } = await supabaseAdmin
            .from('users')
            .select('*')
            .eq('id', decoded.userId)
            .single();

        if (error || !user) {
            return res.status(401).json({ error: 'Invalid or expired token' });
        }

        // Attach user to request
        req.user = {
            id: user.id,
            student_id: user.student_id,
            name: user.name,
            email: user.email,
            role: user.role
        };

        next();
    } catch (error) {
        console.error('Auth middleware error:', error);
        res.status(500).json({ error: 'Authentication failed' });
    }
}

// Middleware to check if user has specific role
function requireRole(...roles) {
    return async (req, res, next) => {
        try {
            if (!req.user) {
                return res.status(401).json({ error: 'Not authenticated' });
            }

            if (!roles.includes(req.user.role)) {
                return res.status(403).json({ error: 'Insufficient permissions' });
            }

            req.userRole = req.user.role;
            next();
        } catch (error) {
            console.error('Role check error:', error);
            res.status(500).json({ error: 'Authorization failed' });
        }
    };
}

module.exports = { authenticateUser, requireRole };
