import { Controller, Get } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { Public } from '../common/decorators/public.decorator';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';

interface HealthResponse {
  status: 'ok' | 'error';
  timestamp: string;
  version: string;
  services: {
    database: 'up' | 'down';
    redis: 'up' | 'down';
  };
}

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

  @Get()
  @Public()
  @ApiOperation({ summary: 'Health-Check fuer alle Services' })
  async check(): Promise<HealthResponse> {
    const [dbStatus, redisStatus] = await Promise.allSettled([
      this.checkDatabase(),
      this.checkRedis(),
    ]);

    const allUp =
      dbStatus.status === 'fulfilled' &&
      dbStatus.value &&
      redisStatus.status === 'fulfilled' &&
      redisStatus.value;

    return {
      status: allUp ? 'ok' : 'error',
      timestamp: new Date().toISOString(),
      version: '0.1.0',
      services: {
        database:
          dbStatus.status === 'fulfilled' && dbStatus.value ? 'up' : 'down',
        redis:
          redisStatus.status === 'fulfilled' && redisStatus.value
            ? 'up'
            : 'down',
      },
    };
  }

  private async checkDatabase(): Promise<boolean> {
    try {
      await this.prisma.$queryRaw`SELECT 1`;
      return true;
    } catch {
      return false;
    }
  }

  private async checkRedis(): Promise<boolean> {
    try {
      const pong = await this.redis.ping();
      return pong === 'PONG';
    } catch {
      return false;
    }
  }
}
