import type { FastifyInstance } from 'fastify';
import cors from '@fastify/cors';
import helmet from '@fastify/helmet';
import rateLimit from '@fastify/rate-limit';
import type { McpdConfig } from '../config/index.js';

export async function registerSecurityPlugins(
  app: FastifyInstance,
  config: McpdConfig,
): Promise<void> {
  await app.register(cors, {
    origin: config.corsOrigins,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
  });

  await app.register(helmet, {
    contentSecurityPolicy: false, // API server, no HTML
  });

  await app.register(rateLimit, {
    max: config.rateLimitMax,
    timeWindow: config.rateLimitWindowMs,
    allowList: (req) => {
      // Exempt health probes and internal monitoring from rate limiting
      const url = req.url;
      return url === '/healthz' || url === '/health';
    },
  });
}
