package observability

import (
	"fmt"

	"xorm.io/xorm"

	"github.com/forgeo/forgebucket/internal/events"
)

const Version = "0.8.0"

// HealthStatus is the response shape for GET /health.
type HealthStatus struct {
	Status  string            `json:"status"`  // "healthy" | "degraded"
	Checks  map[string]string `json:"checks"`  // dependency name → "ok" | error message
	Version string            `json:"version"`
}

// Check pings each critical dependency and returns a HealthStatus.
// HTTP status should be 200 when Status=="healthy", 503 when "degraded".
func Check(db *xorm.Engine, bus events.EventBus) HealthStatus {
	checks := make(map[string]string, 2)

	// Database — attempt a lightweight ping.
	if err := db.Ping(); err != nil {
		checks["database"] = fmt.Sprintf("error: %v", err)
	} else {
		checks["database"] = "ok"
	}

	// NATS — use the Healthy() method added in Phase 3E.
	if bus.Healthy() {
		checks["nats"] = "ok"
	} else {
		checks["nats"] = "disconnected"
	}

	overall := "healthy"
	for _, v := range checks {
		if v != "ok" {
			overall = "degraded"
			break
		}
	}

	return HealthStatus{
		Status:  overall,
		Checks:  checks,
		Version: Version,
	}
}
