package healthchecks

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

var (
	serviceName  = "oos-service"
	version      = "0.1.0"
	environment  = "unknown"
	shuttingDown atomic.Bool
)

// Init sets runtime metadata that is exposed via /health-check.
func Init(env string) {
	environment = env
}

type healthResponse struct {
	Name        string            `json:"name"`
	Version     string            `json:"version"`
	Environment string            `json:"environment"`
	Status      string            `json:"status"`
	Checks      map[string]string `json:"checks,omitempty"`
}

func SetServiceShuttingDown() {
	shuttingDown.Store(true)
}

func CreateHealthHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		resp := healthResponse{
			Name:        serviceName,
			Version:     version,
			Environment: environment,
			Status:      "ok",
			Checks:      make(map[string]string),
		}

		if shuttingDown.Load() {
			resp.Status = "critical"
			resp.Checks["shutting_down"] = "Service is shutting down"
			w.WriteHeader(http.StatusServiceUnavailable)
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(resp)
	})
}

// CreateProbeHandler is a lightweight liveness probe. Returns 200 unless the
// service is in the process of shutting down.
func CreateProbeHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		resp := healthResponse{
			Name:        serviceName,
			Version:     version,
			Environment: environment,
			Status:      "ok",
		}

		if shuttingDown.Load() {
			resp.Status = "critical"
			resp.Checks = map[string]string{"shutting_down": "Service is shutting down"}
			w.WriteHeader(http.StatusServiceUnavailable)
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(resp)
	})
}
