import { Controller, Get, Post, Body, Query } from '@nestjs/common';
import { HealthCheckResultRepository } from '../../../infrastructure/repositories/health-check-result.repository';
import { HealthCheckResult } from '../../../domain/entities/health-check-result.entity';
import * as crypto from 'crypto';

@Controller('api/v1/monitor/health-checks')
export class HealthCheckController {
  constructor(private readonly healthCheckResultRepo: HealthCheckResultRepository) {}

  @Get()
  async listHealthChecks(@Query('serverId') serverId?: string) {
    if (serverId) {
      return this.healthCheckResultRepo.findByServerId(serverId);
    }
    return this.healthCheckResultRepo.findRecent();
  }

  @Post('run')
  async runHealthCheck(@Body() body: { serverIds?: string[]; checkType?: string }) {
    const results: HealthCheckResult[] = [];
    const serverIds = body.serverIds || [];
    const checkType = (body.checkType as HealthCheckResult['checkType']) || 'ping';

    for (const serverId of serverIds) {
      const result = new HealthCheckResult();
      result.id = crypto.randomUUID();
      result.serverId = serverId;
      result.checkType = checkType;
      result.status = 'pending';
      result.checkedAt = new Date();
      result.createdAt = new Date();
      const saved = await this.healthCheckResultRepo.save(result);
      results.push(saved);
    }

    return { message: 'Health checks initiated', results };
  }
}
