import { getPool } from "../db/pool";
import { getMqttPublisherStatus } from "./mqttPublisher";
import { getMqttSubscriberStatus } from "./mqttSubscriber";

export async function getDatabaseHealth() {
  const startedAt = process.hrtime.bigint();
  try {
    const result = await getPool().query("SELECT NOW() AS now");
    const durationMs = Number(process.hrtime.bigint() - startedAt) / 1_000_000;
    return {
      status: "ok" as const,
      latency_ms: Number(durationMs.toFixed(2)),
      server_time: result.rows[0]?.now || null
    };
  } catch (error) {
    const durationMs = Number(process.hrtime.bigint() - startedAt) / 1_000_000;
    return {
      status: "error" as const,
      latency_ms: Number(durationMs.toFixed(2)),
      error: error instanceof Error ? error.message : "unknown"
    };
  }
}

export async function getServiceHealth() {
  const database = await getDatabaseHealth();
  const mqttPublisher = getMqttPublisherStatus();
  const mqttSubscriber = getMqttSubscriberStatus();
  const brokerRequired = mqttPublisher.mode === "broker";
  const mqttOk = !brokerRequired || mqttPublisher.connected || mqttPublisher.publish_attempt_count === 0;

  return {
    status: database.status === "ok" && mqttOk ? "healthy" : "degraded",
    checks: {
      database,
      mqtt: {
        publisher: mqttPublisher,
        subscriber: mqttSubscriber
      }
    }
  };
}
