import type { FastifyInstance } from 'fastify';
import type { HealthAggregator } from '../services/health-aggregator.js';
import type { MetricsCollector } from '../services/metrics-collector.js';

export interface HealthMonitoringDeps {
  healthAggregator: HealthAggregator;
  metricsCollector: MetricsCollector;
}

export function registerHealthMonitoringRoutes(app: FastifyInstance, deps: HealthMonitoringDeps): void {
  app.get('/api/v1/health/overview', async () => {
    return deps.healthAggregator.getOverview();
  });

  app.get<{ Params: { id: string } }>('/api/v1/health/instances/:id', async (request, reply) => {
    const health = deps.healthAggregator.getInstanceHealth(request.params.id);
    if (!health) {
      reply.code(404);
      return { error: `Instance '${request.params.id}' not found`, statusCode: 404 };
    }
    return health;
  });

  app.get('/api/v1/metrics', async () => {
    const allMetrics = deps.metricsCollector.getAllMetrics();
    return {
      instances: allMetrics.map((m) => ({
        instanceId: m.instanceId,
        status: m.status,
        uptime: m.uptime,
        requestCount: m.requestCount,
        errorCount: m.errorCount,
        errorRate: m.requestCount > 0 ? m.errorCount / m.requestCount : 0,
        lastRequestAt: m.lastRequestAt?.toISOString() ?? null,
      })),
      timestamp: new Date().toISOString(),
    };
  });
}
