import { Controller, Get, HttpStatus, Res } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { IsPublic } from '@tria-plc/api-common/modules/auth/decorators/public.decorator';
import { PrismaService } from '../../common/prisma.service';
import { Response } from 'express';

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

  @Get()
  @IsPublic()
  @ApiOperation({ summary: 'Liveness probe' })
  liveness() {
    return { status: 'ok', timestamp: new Date().toISOString() };
  }

  @Get('ready')
  @IsPublic()
  @ApiOperation({ summary: 'Readiness probe — checks database connectivity' })
  async readiness(@Res() res: Response) {
    const start = Date.now();
    try {
      await this.prisma.$queryRaw`SELECT 1`;
      return res.status(HttpStatus.OK).json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        checks: { database: { status: 'ok', latencyMs: Date.now() - start } },
      });
    } catch (err) {
      return res.status(HttpStatus.SERVICE_UNAVAILABLE).json({
        status: 'error',
        timestamp: new Date().toISOString(),
        checks: {
          database: {
            status: 'error',
            latencyMs: Date.now() - start,
            error: err instanceof Error ? err.message : 'Unknown error',
          },
        },
      });
    }
  }

  @Get('info')
  @IsPublic()
  @ApiOperation({ summary: 'App info — version, environment, uptime' })
  info() {
    return {
      name: 'edr-passenger-api',
      version: process.env.npm_package_version ?? '1.0.0',
      environment: process.env.NODE_ENV ?? 'development',
      uptimeSeconds: Math.floor(process.uptime()),
      timestamp: new Date().toISOString(),
    };
  }
}
