import { Controller, Get, Query } from '@nestjs/common';
import { MetricSnapshotRepository } from '../../../infrastructure/repositories/metric-snapshot.repository';
import { HealthCheckResultRepository } from '../../../infrastructure/repositories/health-check-result.repository';

@Controller('api/v1/monitor/metrics')
export class MetricsController {
  constructor(
    private readonly metricSnapshotRepo: MetricSnapshotRepository,
    private readonly healthCheckResultRepo: HealthCheckResultRepository,
  ) {}

  @Get('overview')
  async getOverview() {
    // Aggregate metrics from recent snapshots
    const recentHealthChecks = await this.healthCheckResultRepo.findRecent();

    const serverMap = new Map<string, { status: string; host?: string }>();
    for (const hc of recentHealthChecks) {
      if (!serverMap.has(hc.serverId)) {
        serverMap.set(hc.serverId, {
          status: hc.status === 'healthy' ? 'online' : 'offline',
          host: hc.serverHost,
        });
      }
    }

    const totalServers = serverMap.size || 0;
    const onlineCount = [...serverMap.values()].filter((s) => s.status === 'online').length;
    const onlinePercent = totalServers > 0 ? Math.round((onlineCount / totalServers) * 100) : 0;

    return {
      data: {
        totalServers,
        onlinePercent,
        avgCpuPercent: 0,
        avgMemoryPercent: 0,
        totalAlertsToday: 0,
      },
    };
  }

  @Get('servers')
  async getServerMetrics(
    @Query('environment') environment?: string,
    @Query('status') status?: string,
    @Query('search') search?: string,
  ) {
    const recentHealthChecks = await this.healthCheckResultRepo.findRecent();

    // Group by serverId, taking the latest check per server
    const serverLatest = new Map<string, any>();
    for (const hc of recentHealthChecks) {
      const existing = serverLatest.get(hc.serverId);
      if (!existing || new Date(hc.checkedAt) > new Date(existing.checkedAt)) {
        serverLatest.set(hc.serverId, hc);
      }
    }

    let data = [...serverLatest.values()].map((hc) => ({
      id: hc.serverId,
      hostname: hc.serverHost || hc.serverId.slice(0, 8),
      environment: 'prod' as const,
      status: hc.status === 'healthy' ? 'online' : 'offline',
      cpuPercent: 0,
      memoryPercent: 0,
      diskPercent: 0,
      lastCheckedAt: hc.checkedAt?.toISOString?.() ?? new Date().toISOString(),
    }));

    // Apply filters
    if (status && status !== 'all') {
      data = data.filter((s) => s.status === status);
    }
    if (environment && environment !== 'all') {
      data = data.filter((s) => s.environment === environment);
    }
    if (search) {
      const q = search.toLowerCase();
      data = data.filter((s) => s.hostname.toLowerCase().includes(q));
    }

    return { data, total: data.length };
  }
}
