/**
 * Admin Central API auth middleware
 * Used for service-to-service calls from orchestration portal, token-aggregation, multi-chain-execution.
 * Expects X-Admin-Central-Key header to match ADMIN_CENTRAL_API_KEY env.
 */

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

export function requireAdminCentralKey(req: Request, res: Response, next: NextFunction): void {
  const key = req.headers['x-admin-central-key'] as string | undefined;
  const expected = process.env.ADMIN_CENTRAL_API_KEY;

  if (!expected) {
    // If not configured, allow (dev) or deny (prod). Prefer deny for security.
    res.status(501).json({
      success: false,
      error: { code: 'NOT_CONFIGURED', message: 'Admin central API key not configured' },
    });
    return;
  }

  if (!key || key !== expected) {
    res.status(401).json({
      success: false,
      error: { code: 'UNAUTHORIZED', message: 'Invalid or missing X-Admin-Central-Key' },
    });
    return;
  }

  next();
}
