import { Request, Response, NextFunction } from 'express';
import { env } from '../../main/config/env';

export const apiKeyMiddleware = (req: Request, res: Response, next: NextFunction): void => {
  const providedKey = req.headers['x-api-key'];

  if (!env.ADMIN_API_KEY) {
    res.status(500).json({
      success: false,
      code: 'SERVER_CONFIGURATION_ERROR',
      message: 'Admin API key is not configured',
    });
    return;
  }

  if (providedKey !== env.ADMIN_API_KEY) {
    res.status(401).json({
      success: false,
      code: 'UNAUTHORIZED',
      message: 'Invalid or missing admin API key',
    });
    return;
  }

  next();
};
