import {
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  Logger,
  ServiceUnavailableException,
} from '@nestjs/common';
import { hostname } from 'node:os';

import { ObservabilityCoreService } from '../modules/free/observability/core/observability-core/observability-core.service';

@Controller('api/health/module')
export class ObservabilityCoreHealthController {
  private readonly logger = new Logger(ObservabilityCoreHealthController.name);

  constructor(private readonly observabilityService: ObservabilityCoreService) {}

  @Get('{{ module_kebab }}')
  @HttpCode(HttpStatus.OK)
  getModuleHealth(): Record<string, unknown> {
    try {
      const summary = this.observabilityService.getSummary();
      return {
        status: summary.status,
        module: summary.module,
        service_name: summary.serviceName,
        environment: summary.environment,
        hostname: hostname(),
        metrics: summary.metrics,
        tracing: summary.tracing,
        events: summary.events,
      };
    } catch (error) {
      const detail =
        error instanceof Error && error.message ? error.message : 'observability health check failed';
      this.logger.error(`Observability health check failed: ${detail}`);
      throw new ServiceUnavailableException({
        status: 'error',
        module: '{{ rapidkit_vendor_module }}',
        detail,
      });
    }
  }
}
