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

/**
 * API Key Authentication Middleware
 * Validates X-Admin-API-Key header for admin API endpoints
 */
const validateApiKey = (req, res, next) => {
    // Only validate admin API endpoints, not admin pages
    // Exclude the login endpoint since that's where you authenticate TO get the API key
    if (!req.path.startsWith('/admin/api') && !req.path.startsWith('/webhook')) {
        return next();
    }
    
    // Skip API key validation for the login endpoint itself
    if (req.path === '/admin/api-login') {
        return next();
    }
    
    const apiKey = req.headers['x-admin-api-key'] || req.headers['authorization']?.replace('Bearer ', '');
    
    if (!apiKey) {
        auditLog('API_KEY_MISSING', { 
            path: req.path, 
            ip: req.ip,
            userAgent: req.get('User-Agent')
        }, req);
        
        return res.status(401).json({
            success: false,
            message: 'API key required',
            requestId: req.requestId
        });
    }
    
    // Check against configured API key
    if (apiKey !== config.ADMIN_API_KEY) {
        auditLog('API_KEY_INVALID', { 
            path: req.path, 
            ip: req.ip,
            providedKey: apiKey.substring(0, 8) + '...',
            userAgent: req.get('User-Agent')
        }, req);
        
        return res.status(403).json({
            success: false,
            message: 'Invalid API key',
            requestId: req.requestId
        });
    }
    
    auditLog('API_KEY_VALID', { 
        path: req.path, 
        ip: req.ip 
    }, req);
    
    next();
};

module.exports = { validateApiKey };
