import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
import { emitBatchMetrics, emitError } from '@shieldai/monitoring';

const SERVICE_NAME = process.env.DD_SERVICE || 'shieldai-api';

export async function monitoringMiddleware(fastify: FastifyInstance) {
  fastify.addHook('onResponse', async (request: FastifyRequest, reply: FastifyReply) => {
    const statusCode = reply.statusCode;
    const responseTime = reply.elapsedTime;
    const method = request.method;
    const url = request.url;

    // Batch all metrics into a single PutMetricDataCommand to avoid rate limits
    await emitBatchMetrics({
      serviceName: SERVICE_NAME,
      data: [
        {
          metricName: 'api_requests',
          value: 1,
          unit: 'Count',
          dimensions: { status_class: String(Math.floor(statusCode / 100)) + 'xx' },
        },
        {
          metricName: 'api_latency',
          value: responseTime,
          unit: 'Milliseconds',
          dimensions: { percentile: 'p50' },
        },
        {
          metricName: 'api_latency',
          value: responseTime,
          unit: 'Milliseconds',
          dimensions: { percentile: 'p95' },
        },
        {
          metricName: 'api_latency',
          value: responseTime,
          unit: 'Milliseconds',
          dimensions: { percentile: 'p99' },
        },
      ],
    });

    // Emit error metric for 5xx (separate call since it has different dimensions)
    if (statusCode >= 500) {
      await emitError(SERVICE_NAME, 'server_error');
      fastify.log.warn({
        event: 'high_latency_or_error',
        method,
        url,
        statusCode,
        responseTime,
        service: SERVICE_NAME,
      });
    }

    // Log high latency requests (>2s) — only when not already logged as error
    else if (responseTime > 2000) {
      fastify.log.warn({
        event: 'high_latency',
        method,
        url,
        statusCode,
        responseTime,
        service: SERVICE_NAME,
      });
    }
  });
}
