/**
 * Prometheus Metrics Endpoint
 * Agent 4: Production Deployment
 *
 * GET /api/metrics
 * Returns application metrics in Prometheus format.
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { metrics } from '../../lib/monitoring';
import { env } from '../../lib/config';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    res.setHeader('Allow', ['GET']);
    return res.status(405).end('Method Not Allowed');
  }

  // Only expose metrics if enabled
  if (!env.prometheusEnabled && env.isProduction) {
    return res.status(403).end('Metrics endpoint disabled');
  }

  try {
    const metricsOutput = metrics.toPrometheusFormat();

    res.setHeader('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
    res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');

    return res.status(200).end(metricsOutput);
  } catch (error) {
    return res.status(500).end('Failed to generate metrics');
  }
}
