package observability

import (
	"encoding/json"
	"net/http"
	"sync/atomic"
)

// HealthStatus represents the health status of the service.
type HealthStatus struct {
	Status string `json:"status"`
}

// HealthChecker provides health check endpoints.
type HealthChecker struct {
	ready atomic.Bool
}

// NewHealthChecker creates a new health checker.
func NewHealthChecker() *HealthChecker {
	return &HealthChecker{}
}

// SetReady sets the ready state.
func (h *HealthChecker) SetReady(ready bool) {
	h.ready.Store(ready)
}

// IsReady returns the ready state.
func (h *HealthChecker) IsReady() bool {
	return h.ready.Load()
}

// LivenessHandler returns an HTTP handler for liveness checks.
func (h *HealthChecker) LivenessHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(HealthStatus{Status: "ok"})
	}
}

// ReadinessHandler returns an HTTP handler for readiness checks.
func (h *HealthChecker) ReadinessHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")

		if !h.IsReady() {
			w.WriteHeader(http.StatusServiceUnavailable)
			_ = json.NewEncoder(w).Encode(HealthStatus{Status: "not ready"})
			return
		}

		w.WriteHeader(http.StatusOK)
		_ = json.NewEncoder(w).Encode(HealthStatus{Status: "ready"})
	}
}
