import { Injectable } from '@nestjs/common';
import { getConfig } from '@hexahost/config';
import type { HealthCheck, HealthResponse } from '@hexahost/contracts';

import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class HealthService {
  constructor(private readonly prisma: PrismaService) {}

  getLive(): HealthResponse {
    const config = getConfig();

    return {
      status: 'ok',
      service: config.APP_NAME,
      timestamp: new Date().toISOString(),
    };
  }

  async getReady(): Promise<HealthResponse> {
    const config = getConfig();
    const checks: HealthCheck[] = [];
    const startedAt = Date.now();

    try {
      await this.prisma.$queryRaw`SELECT 1`;
      checks.push({
        name: 'database',
        status: 'ok',
        durationMs: Date.now() - startedAt,
      });
    } catch (error) {
      checks.push({
        name: 'database',
        status: 'error',
        message: error instanceof Error ? error.message : 'Database check failed',
        durationMs: Date.now() - startedAt,
      });
    }

    const hasError = checks.some((check) => check.status === 'error');

    return {
      status: hasError ? 'error' : 'ok',
      service: config.APP_NAME,
      timestamp: new Date().toISOString(),
      checks,
    };
  }
}
