package handler

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

	"github.com/gin-gonic/gin"
	"github.com/redis/go-redis/v9"
)

type Health struct {
	db    *sql.DB
	redis *redis.Client
}

func NewHealth(db *sql.DB, redisClient *redis.Client) *Health {
	return &Health{db: db, redis: redisClient}
}

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

	services := map[string]string{
		"postgresql": "ok",
		"redis":      "ok",
	}
	status := "ok"
	statusCode := http.StatusOK

	if err := h.db.PingContext(ctx); err != nil {
		services["postgresql"] = "unavailable"
		status = "degraded"
		statusCode = http.StatusServiceUnavailable
	}
	if err := h.redis.Ping(ctx).Err(); err != nil {
		services["redis"] = "unavailable"
		status = "degraded"
		statusCode = http.StatusServiceUnavailable
	}

	c.JSON(statusCode, gin.H{
		"status":   status,
		"services": services,
	})
}
