import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';

export interface HealthStatus {
  status: 'healthy' | 'degraded' | 'unhealthy';
  service: string;
  timestamp: string;
  uptime: number;
  checks: {
    database: {
      status: 'ok' | 'error';
      responseTime: number;
      details?: string;
    };
  };
}

@Injectable()
export class HealthService {
  private readonly startTime = Date.now();

  constructor(private readonly prisma: PrismaService) {}

  async getOverallHealth(): Promise<{
    status: 'healthy' | 'degraded' | 'unhealthy';
    statusCode: number;
    service: string;
    timestamp: string;
    uptime: number;
    checks: {
      database: {
        status: 'ok' | 'error';
        responseTime: number;
        details?: string;
      };
    };
  }> {
    const timestamp = new Date().toISOString();
    const uptime = Date.now() - this.startTime;

    // Testa databaskopplingen
    const dbStart = Date.now();
    let dbStatus: 'ok' | 'error' = 'ok';
    let dbResponseTime = 0;
    let dbDetails: string | undefined;

    try {
      await this.prisma.$queryRaw`SELECT 1`;
      dbResponseTime = Date.now() - dbStart;
    } catch (error) {
      dbStatus = 'error';
      dbResponseTime = Date.now() - dbStart;
      dbDetails = error instanceof Error ? error.message : 'Unknown database error';
    }

    // Bestäm övergripande hälsa
    let overallStatus: 'healthy' | 'degraded' | 'unhealthy' = 'healthy';
    if (dbStatus === 'error') {
      overallStatus = 'unhealthy';
    }

    const statusCode = overallStatus === 'unhealthy' ? 503 : 200;

    return {
      status: overallStatus,
      statusCode,
      service: 'recipe-api',
      timestamp,
      uptime,
      checks: {
        database: {
          status: dbStatus,
          responseTime: dbResponseTime,
          details: dbDetails,
        },
      },
    };
  }

  async getDatabaseHealth(): Promise<{
    status: 'ok' | 'error';
    database: string;
    responseTime: number;
    timestamp: string;
    details?: string;
    statusCode: number;
  }> {
    const timestamp = new Date().toISOString();
    const startTime = Date.now();

    try {
      await this.prisma.$queryRaw`SELECT 1`;
      const responseTime = Date.now() - startTime;

      return {
        status: 'ok',
        database: 'connected',
        responseTime,
        timestamp,
        statusCode: 200,
      };
    } catch (error) {
      const responseTime = Date.now() - startTime;
      const details = error instanceof Error ? error.message : 'Unknown database error';

      return {
        status: 'error',
        database: 'not reachable',
        responseTime,
        timestamp,
        details,
        statusCode: 503,
      };
    }
  }
}
