import { Controller, Get, HttpStatus, HttpCode } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { PrismaService } from '@chatapp/database';
import { RedisService } from '@chatapp/redis';

@ApiTags('Health')
@Controller('health')
export class HealthController {
  constructor(
    private readonly prisma: PrismaService,
    private readonly redis: RedisService,
  ) {}

  @Get()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Liveness probe — checks if the process is alive' })
  liveness() {
    return {
      status: 'ok',
      service: 'chatapp-api',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
    };
  }

  @Get('ready')
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Readiness probe — checks all dependencies' })
  async readiness() {
    const checks: Record<string, { status: string; latency?: number; error?: string }> = {};

    // PostgreSQL check
    try {
      const start = Date.now();
      await this.prisma.$queryRaw`SELECT 1`;
      checks.database = { status: 'ok', latency: Date.now() - start };
    } catch (err) {
      checks.database = { status: 'error', error: (err as Error).message };
    }

    // Redis check
    try {
      const start = Date.now();
      await this.redis.client.ping();
      checks.redis = { status: 'ok', latency: Date.now() - start };
    } catch (err) {
      checks.redis = { status: 'error', error: (err as Error).message };
    }

    const allOk = Object.values(checks).every((c) => c.status === 'ok');
    const httpStatus = allOk ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE;

    return {
      status: allOk ? 'ok' : 'degraded',
      service: 'chatapp-api',
      timestamp: new Date().toISOString(),
      checks,
    };
  }
}