import { Controller, Get, Res } from '@nestjs/common';
import { SkipThrottle } from '@nestjs/throttler';
import type { Response } from 'express';
import { PdfService } from '../documents/pdf.service';
import { PrismaService } from '../prisma/prisma.service';

@SkipThrottle()
@Controller('health')
export class HealthController {
  constructor(
    private readonly prisma: PrismaService,
    private readonly pdf: PdfService,
  ) {}

  @Get()
  liveness() {
    return { status: 'ok', service: 'rms-api', time: new Date().toISOString() };
  }

  @Get('ready')
  async readiness(@Res({ passthrough: true }) res: Response) {
    const db = await this.prisma.isHealthy();
    // The PDF renderer is reported but does NOT make the service unready: the
    // system runs fine without it right up until somebody prints a debit note.
    // Reporting it is what lets a deploy notice, instead of a tenant noticing.
    const renderer = this.pdf.rendererStatus();
    // 503 when the DB is down so load balancers / orchestrators stop routing here.
    res.status(db ? 200 : 503);
    return {
      status: db ? 'ok' : 'degraded',
      database: db ? 'up' : 'down',
      pdfRenderer: renderer.ok ? 'up' : 'missing',
      ...(renderer.ok ? {} : { pdfRendererDetail: renderer.detail }),
    };
  }
}
