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

import { DbMongoService } from '../modules/free/database/db_mongo/db-mongo.service';

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

  constructor(private readonly dbMongoService: DbMongoService) {}

  @Get('db-mongo')
  @HttpCode(HttpStatus.OK)
  async getMongoHealth(): Promise<Record<string, unknown>> {
    try {
      const payload = await this.dbMongoService.checkHealth();
      this.logger.debug(`Mongo health payload=${JSON.stringify(payload)}`);
      return {
        status: payload.status,
        detail: payload.detail,
        module: payload.module,
        metrics: payload.metrics,
        replica: payload.replica,
        server_version: payload.server_version,
        hostname: hostname(),
        extra: payload.extra,
        errors: payload.errors,
      };
    } catch (error) {
      const message =
        error instanceof Error && error.message
          ? error.message
          : 'mongo health check failed';
      this.logger.error(`Mongo health check failed: ${message}`);
      throw new ServiceUnavailableException({
        status: 'error',
        module: '{{ rapidkit_vendor_module }}',
        detail: message,
      });
    }
  }
}
