package su.xserver.iikocon.service;

import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.healthchecks.Status;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.healthchecks.HealthCheckHandler;

import java.util.Collections;

public class HealthCheckService {

  private final RedisService redisService;
  private final DataBaseService dbService;
  private final Vertx vertx;

  public HealthCheckService(Vertx vertx, RedisService redisService, DataBaseService dbService) {
    this.vertx = vertx;
    this.redisService = redisService;
    this.dbService = dbService;
  }

  public void registerHealthCheck(Router router) {
    HealthCheckHandler healthCheckHandler = HealthCheckHandler.create(vertx);

    // Redis check
    healthCheckHandler.register("redis", future -> {
      long start = System.currentTimeMillis();
      redisService.getRedisApi().ping(Collections.emptyList())
        .onSuccess(response -> {
          long time = System.currentTimeMillis() - start;
          if ("PONG".equalsIgnoreCase(response.toString())) {
            JsonObject data = new JsonObject()
              .put("name", "Redis")
              .put("latency_ms", time);
            future.complete(Status.OK(data));
          } else {
            future.tryFail("Unexpected Redis response: " + response);
          }
        })
        .onFailure(err -> future.tryFail("Redis ping failed: " + err.getMessage()));
    });

    // Database check
    healthCheckHandler.register("database", future -> {
      long start = System.currentTimeMillis();
      dbService.getPool().query("SELECT 1").execute()
        .onSuccess(rs -> {
          long time = System.currentTimeMillis() - start;
          JsonObject data = new JsonObject()
            .put("name", "DataBase")
            .put("latency_ms", time);
          future.complete(Status.OK(data));
        })
        .onFailure(err -> future.tryFail("DataBase ping failed: " + err.getMessage()));
    });

    // Endpoint /api/health
    router.get("/api/health").handler(healthCheckHandler);
  }
}
