package handlers

import (
	"context"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/redis/go-redis/v9"
)

type HealthHandler struct {
	db    *pgxpool.Pool
	cache *redis.Client
}

func NewHealthHandler(db *pgxpool.Pool, cache *redis.Client) *HealthHandler {
	return &HealthHandler{db: db, cache: cache}
}

func (h *HealthHandler) Live(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"status": "ok", "timestamp": time.Now().UTC()})
}

func (h *HealthHandler) Ready(c *gin.Context) {
	ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
	defer cancel()

	health := gin.H{"status": "ready"}

	if err := h.db.Ping(ctx); err != nil {
		health["status"] = "degraded"
		health["postgres"] = err.Error()
		c.JSON(http.StatusServiceUnavailable, health)
		return
	}

	if err := h.cache.Ping(ctx).Err(); err != nil {
		health["status"] = "degraded"
		health["dragonfly"] = err.Error()
		c.JSON(http.StatusServiceUnavailable, health)
		return
	}

	health["postgres"] = "ok"
	health["dragonfly"] = "ok"
	c.JSON(http.StatusOK, health)
}
