import { NextResponse } from "next/server"
import { healthCheck, getPoolStats } from "@/lib/database"

export async function GET() {
  try {
    const health = await healthCheck()
    const poolStats = getPoolStats()

    return NextResponse.json({
      ...health,
      poolStats,
      recommendations: generateRecommendations(poolStats),
    })
  } catch (error) {
    console.error("Database health check error:", error)
    return NextResponse.json(
      {
        status: "error",
        error: error instanceof Error ? error.message : "Unknown error",
        timestamp: new Date().toISOString(),
      },
      { status: 500 },
    )
  }
}

function generateRecommendations(stats: any) {
  const recommendations = []

  if (!stats) {
    recommendations.push("Unable to get pool statistics")
    return recommendations
  }

  const utilizationRate = (stats.totalConnections - stats.freeConnections) / stats.connectionLimit

  if (utilizationRate > 0.8) {
    recommendations.push("High connection utilization - consider increasing connection limit")
  }

  if (stats.acquiringConnections > 5) {
    recommendations.push("Many connections waiting - possible connection leak or high load")
  }

  if (stats.freeConnections === 0) {
    recommendations.push("No free connections available - increase pool size or check for connection leaks")
  }

  if (recommendations.length === 0) {
    recommendations.push("Database pool is healthy")
  }

  return recommendations
}
