package health

import (
	"context"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5/pgxpool"
	"go.uber.org/zap"
)

type Handler struct {
	log  *zap.SugaredLogger
	pool *pgxpool.Pool
}

func NewHandler(log *zap.SugaredLogger, pool *pgxpool.Pool) *Handler {
	return &Handler{
		log:  log,
		pool: pool,
	}
}

func (h *Handler) RegisterRoutes(rg *gin.RouterGroup) {
	rg.GET("/live", h.Live)
	rg.GET("/ready", h.Ready)
}

func (h *Handler) Live(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"status": "alive"})
}

func (h *Handler) Ready(c *gin.Context) {
	ctx := context.Background()
	if err := h.pool.Ping(ctx); err != nil {
		h.log.Warnw("health check: db ping failed", "error", err)
		c.JSON(http.StatusServiceUnavailable, gin.H{"status": "not ready", "error": "db unreachable"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": "ready"})
}
