import { getPoolStats } from "./database"

let monitoringInterval: NodeJS.Timeout | null = null

export function startConnectionMonitoring() {
  if (monitoringInterval) {
    return // Already monitoring
  }

  console.log("Starting database connection monitoring...")

  monitoringInterval = setInterval(() => {
    const stats = getPoolStats()
    if (stats) {
      const utilizationRate = (stats.totalConnections - stats.freeConnections) / stats.connectionLimit

      console.log(
        `DB Pool Stats: ${stats.totalConnections}/${stats.connectionLimit} total, ${stats.freeConnections} free, ${stats.acquiringConnections} acquiring (${Math.round(utilizationRate * 100)}% utilization)`,
      )

      // Warn if utilization is high
      if (utilizationRate > 0.8) {
        console.warn("⚠️  High database connection utilization detected!")
      }

      // Warn if many connections are waiting
      if (stats.acquiringConnections > 3) {
        console.warn("⚠️  Many connections waiting for pool!")
      }
    }
  }, 30000) // Every 30 seconds
}

export function stopConnectionMonitoring() {
  if (monitoringInterval) {
    clearInterval(monitoringInterval)
    monitoringInterval = null
    console.log("Stopped database connection monitoring")
  }
}

// Auto-start monitoring in production
if (process.env.NODE_ENV === "production") {
  startConnectionMonitoring()
}
