import { Controller, Get } from '@nestjs/common';

/**
 * Standard health check endpoint for all services.
 * Used by Kong, K8s readiness/liveness probes, and docker healthcheck.
 *
 * GET /health        → { status: 'ok', service, uptime, timestamp }
 * GET /health/ready  → 200 if service is ready to accept traffic
 * GET /health/live   → 200 if service is alive
 */
@Controller('health')
export class HealthController {
  private readonly startTime = Date.now();
  private readonly serviceName: string;
  private isReady = true;

  constructor() {
    this.serviceName = process.env.SERVICE_NAME || 'unknown';
  }

  @Get()
  health() {
    return {
      status: 'ok',
      service: this.serviceName,
      uptime: Math.floor((Date.now() - this.startTime) / 1000),
      timestamp: new Date().toISOString(),
    };
  }

  @Get('ready')
  readiness() {
    if (!this.isReady) {
      return { status: 'not_ready' };
    }
    return { status: 'ready' };
  }

  @Get('live')
  liveness() {
    return { status: 'alive' };
  }

  /**
   * Set readiness state. Call with false during graceful shutdown.
   */
  setReady(ready: boolean) {
    this.isReady = ready;
  }
}
