import { Injectable, Logger } from "@nestjs/common";
import { ValkeyService } from "../../valkey/valkey.service";

export interface ReadinessResult {
  ready: boolean;
  checks: {
    valkey: boolean;
  };
}

@Injectable()
export class HealthService {
  private readonly startTime: number;
  private readonly logger = new Logger(HealthService.name);

  constructor(private readonly valkeyService: ValkeyService) {
    this.startTime = Date.now();
  }

  getUptime(): number {
    return Math.floor((Date.now() - this.startTime) / 1000);
  }

  /**
   * Check if the service is ready to accept requests
   * Validates connectivity to required dependencies
   */
  async isReady(): Promise<ReadinessResult> {
    const valkeyReady = await this.checkValkey();

    const ready = valkeyReady;

    if (!ready) {
      this.logger.warn(`Readiness check failed: valkey=${String(valkeyReady)}`);
    }

    return {
      ready,
      checks: {
        valkey: valkeyReady,
      },
    };
  }

  private async checkValkey(): Promise<boolean> {
    try {
      return await this.valkeyService.ping();
    } catch (error) {
      this.logger.error(
        "Valkey health check failed",
        error instanceof Error ? error.message : String(error)
      );
      return false;
    }
  }
}
