// AS4 Metrics API Routes
// Exposes Prometheus metrics endpoint

import { Router } from 'express';
import { as4MetricsService } from '@/infrastructure/monitoring/as4-metrics.service';
import prisma from '@/shared/database/prisma';
import { memberDirectoryService } from '../as4-settlement/member-directory/member-directory.service';
import { certificateManagerService } from '../as4-settlement/member-directory/certificate-manager.service';

const router = Router();

/**
 * GET /api/v1/as4/metrics
 * Prometheus metrics endpoint
 */
router.get('/metrics', async (req, res) => {
  try {
    // Update metrics from database
    try {
      // Check database connection
      await prisma.$queryRaw`SELECT 1`;
      as4MetricsService.updateConnectionStatus(1, 0); // Redis check would go here
    } catch (error) {
      as4MetricsService.updateConnectionStatus(0, 0);
    }

    // Update member counts
    try {
      const members = await memberDirectoryService.searchMembers({ status: 'active' });
      as4MetricsService.updateMemberCounts(members.length, members.length);
    } catch (error) {
      // Ignore errors
    }

    // Update certificate expiration warnings
    try {
      const warnings = await certificateManagerService.getExpirationWarnings(30);
      as4MetricsService.updateCertificateCounts(warnings.length, 0);
    } catch (error) {
      // Ignore errors
    }

    // Export metrics
    const metrics = as4MetricsService.exportPrometheusFormat();
    res.set('Content-Type', 'text/plain; version=0.0.4');
    res.send(metrics);
  } catch (error) {
    res.status(500).json({
      error: 'Failed to generate metrics',
      message: error instanceof Error ? error.message : 'Unknown error',
    });
  }
});

/**
 * GET /api/v1/as4/metrics/health
 * Health check with metrics summary
 */
router.get('/metrics/health', async (req, res) => {
  try {
    const metrics = as4MetricsService.getMetrics();
    
    // Check database
    let dbStatus = 'disconnected';
    try {
      await prisma.$queryRaw`SELECT 1`;
      dbStatus = 'connected';
    } catch (error) {
      // Database not available
    }

    // Check Redis
    let redisStatus = 'disconnected';
    // TODO: Add Redis health check

    res.json({
      status: dbStatus === 'connected' ? 'healthy' : 'degraded',
      timestamp: new Date().toISOString(),
      metrics: {
        messages: {
          received: metrics.messagesReceived,
          processed: metrics.messagesProcessed,
          failed: metrics.messagesFailed,
          latencyP99: metrics.messageLatencyP99,
        },
        instructions: {
          received: metrics.instructionsReceived,
          accepted: metrics.instructionsAccepted,
          rejected: metrics.instructionsRejected,
          posted: metrics.instructionsPosted,
          queued: metrics.instructionsQueued,
        },
        members: {
          active: metrics.activeMembers,
          total: metrics.totalMembers,
        },
        certificates: {
          expiringSoon: metrics.certificatesExpiringSoon,
          expired: metrics.certificatesExpired,
        },
      },
      connections: {
        database: dbStatus,
        redis: redisStatus,
      },
    });
  } catch (error) {
    res.status(500).json({
      error: 'Failed to get health metrics',
      message: error instanceof Error ? error.message : 'Unknown error',
    });
  }
});

export default router;
