package api

import zio.*
import zio.http.*
import javax.sql.DataSource

/** Health check endpoints
  *
  * Provides health check endpoints for load balancers and monitoring systems.
  *
  * Endpoints:
  *   - GET /health - Returns 200 OK when server is running (liveness probe)
  *   - GET /ready - Returns 200 when database is connected, 503 when not (readiness probe)
  */
object HealthRoutes {

  val routes: Routes[DataSource, Response] =
    Routes(
      // Liveness probe - always 200 if server is running
      Method.GET / "health" -> Handler.text("ok"),
      // Readiness probe - checks database connectivity
      Method.GET / "ready" -> handler {
        ZIO.serviceWithZIO[DataSource] { ds =>
          ZIO.attempt {
            val conn = ds.getConnection
            conn.close()
          }.as(Response.text("ready"))
            .catchAll(_ => ZIO.succeed(Response.status(Status.ServiceUnavailable)))
        }
      }
    )

}
