import { Controller, Get } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { PrismaService } from '../../infrastructure/persistence/prisma/prisma.service';
import { RedisService } from '../../infrastructure/redis/redis.service';
import { Public } from '../../shared/guards/jwt-auth.guard';

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

  @Get()
  @ApiOperation({ summary: '健康检查' })
  @ApiResponse({ status: 200, description: '服务健康' })
  async check() {
    const status = {
      status: 'healthy' as 'healthy' | 'unhealthy',
      timestamp: new Date().toISOString(),
      services: {
        database: 'up' as 'up' | 'down',
        redis: 'up' as 'up' | 'down',
      },
    };

    try {
      await this.prisma.$queryRaw`SELECT 1`;
    } catch {
      status.services.database = 'down';
      status.status = 'unhealthy';
    }

    try {
      await this.redis.getClient().ping();
    } catch {
      status.services.redis = 'down';
      status.status = 'unhealthy';
    }

    return status;
  }

  @Get('ready')
  @ApiOperation({ summary: '就绪检查' })
  async ready() {
    return { ready: true };
  }

  @Get('live')
  @ApiOperation({ summary: '存活检查' })
  async live() {
    return { alive: true };
  }
}
