// Authentication middleware
const config = require('../config/environment');
const { auditLog } = require('../utils/logging');

// Admin API key authentication middleware
const authenticateAdmin = (req, res, next) => {
    const apiKey = req.headers['x-admin-api-key'];
    
    if (!apiKey || apiKey !== config.ADMIN_API_KEY) {
        auditLog('ADMIN_AUTH_FAILED', { 
            providedKey: apiKey ? 'provided' : 'missing',
            ip: req.ip,
            userAgent: req.get('User-Agent')
        }, req);
        
        return res.status(401).json({
            success: false,
            message: 'Invalid or missing admin API key',
            requestId: req.requestId
        });
    }
    
    auditLog('ADMIN_AUTH_SUCCESS', { ip: req.ip }, req);
    next();
};

// Basic auth for admin login
const authenticateBasicAuth = (req, res, next) => {
    const auth = req.headers.authorization;
    
    if (!auth || !auth.startsWith('Basic ')) {
        res.set('WWW-Authenticate', 'Basic realm="Admin Area"');
        return res.status(401).json({
            success: false,
            message: 'Authentication required'
        });
    }
    
    const credentials = Buffer.from(auth.slice(6), 'base64').toString().split(':');
    const [username, password] = credentials;
    
    if (username !== config.ADMIN_USERNAME || password !== config.ADMIN_PASSWORD) {
        auditLog('ADMIN_LOGIN_FAILED', { 
            username,
            ip: req.ip,
            userAgent: req.get('User-Agent')
        }, req);
        
        res.set('WWW-Authenticate', 'Basic realm="Admin Area"');
        return res.status(401).json({
            success: false,
            message: 'Invalid credentials'
        });
    }
    
    auditLog('ADMIN_LOGIN_SUCCESS', { 
        username,
        ip: req.ip 
    }, req);
    
    next();
};

module.exports = {
    authenticateAdmin,
    authenticateBasicAuth
};
