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

import { RateLimitingService } from '../modules/free/security/rate_limiting/rate-limiting.service';
import { RATE_LIMITING_CONFIG_NAMESPACE } from '../modules/free/security/rate_limiting/rate-limiting.module';

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

  constructor(private readonly rateLimitingService: RateLimitingService) {}

  @Get('rate-limiting')
  @HttpCode(HttpStatus.OK)
  getModuleHealth(): Record<string, unknown> {
    try {
      const metadata = this.rateLimitingService.getMetadata();
      return {
        status: metadata.enabled ? 'ok' : 'disabled',
        module: {{ rapidkit_vendor_module | tojson }},
        namespace: RATE_LIMITING_CONFIG_NAMESPACE,
        hostname: hostname(),
        defaultRule: metadata.defaultRule,
        rules: metadata.rules,
        headers: metadata.headers,
        forwardedForHeader: this.rateLimitingService.getForwardedForHeader(),
        identityHeader: this.rateLimitingService.getIdentityHeaderName(),
        trustForwardedFor: this.rateLimitingService.isForwardedForTrusted(),
      };
    } catch (error) {
      const detail = error instanceof Error && error.message ? error.message : 'rate limiting health check failed';
      this.logger.error(`Rate limiting health check failed: ${detail}`);
      throw new ServiceUnavailableException({
        status: 'error',
        module: {{ rapidkit_vendor_module | tojson }},
        detail,
      });
    }
  }
}
