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

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

  @Get()
  @Public()
  @ApiOperation({ summary: '健康检查' })
  @ApiResponse({ status: 200, description: '服务健康' })
  async check() {
    const checks = {
      service: 'mining-wallet-service',
      status: 'healthy',
      timestamp: new Date().toISOString(),
      checks: {
        database: 'unknown',
        redis: 'unknown',
      },
    };

    // Database check
    try {
      await this.prisma.$queryRaw`SELECT 1`;
      checks.checks.database = 'healthy';
    } catch {
      checks.checks.database = 'unhealthy';
      checks.status = 'degraded';
    }

    // Redis check
    try {
      await this.redis.set('health:check', 'ok', 10);
      checks.checks.redis = 'healthy';
    } catch {
      checks.checks.redis = 'unhealthy';
      checks.status = 'degraded';
    }

    return checks;
  }

  @Get('live')
  @Public()
  @ApiOperation({ summary: 'Liveness 探针' })
  async liveness() {
    return { status: 'ok' };
  }

  @Get('ready')
  @Public()
  @ApiOperation({ summary: 'Readiness 探针' })
  async readiness() {
    try {
      await this.prisma.$queryRaw`SELECT 1`;
      return { status: 'ready' };
    } catch {
      return { status: 'not ready' };
    }
  }
}
