package api

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

// getHealth handles GET /api/health.
func (s *Server) getHealth(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

	now := time.Now().UTC().Format(time.RFC3339)
	result := map[string]any{
		"checked_at": now,
	}

	// Check database connectivity.
	if err := s.store.DB().PingContext(ctx); err != nil {
		result["database"] = map[string]any{"connected": false, "error": "database unreachable"}
	} else {
		result["database"] = map[string]any{"connected": true}
	}

	// Check Docker connectivity.
	if s.docker == nil {
		result["docker"] = map[string]any{
			"connected": false,
			"error":     "docker client not initialized",
		}
	} else if err := s.docker.Ping(ctx); err != nil {
		result["docker"] = map[string]any{
			"connected": false,
			"error":     err.Error(),
		}
	} else {
		result["docker"] = map[string]any{"connected": true}
	}

	// Check proxy provider connectivity.
	if s.proxyProvider != nil {
		providerName := s.proxyProvider.Name()
		if err := s.proxyProvider.Ping(ctx); err != nil {
			result["proxy"] = map[string]any{"provider": providerName, "connected": false, "error": providerName + " unreachable"}
		} else {
			result["proxy"] = map[string]any{"provider": providerName, "connected": true}
		}
	}

	respondJSON(w, http.StatusOK, result)
}
