import { Request, Response, NextFunction } from 'express';

/**
 * Middleware to ensure the API key is a master key
 * Must be used AFTER validateApiKey middleware
 */
export function requireMasterKey(req: Request, res: Response, next: NextFunction): void {
  if (!req.apiKey) {
    res.status(401).json({
      error: 'Authentication required',
      message: 'This endpoint requires authentication',
    });
    return;
  }

  if (req.apiKey.keyType !== 'master') {
    console.warn(
      `[${new Date().toISOString()}] Non-master key attempted admin action: ${req.apiKey.id} (${req.apiKey.keyType}) - ${req.path}`,
    );

    res.status(403).json({
      error: 'Master key required',
      message: 'This endpoint requires a master API key',
    });
    return;
  }

  next();
}
