package system

import (
	"net/http"
	"os"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/AgentTeam/desktop/internal/daemoncontrol"
)

// HealthHandler serves the unauthenticated daemon health check endpoint.
type HealthHandler struct {
	identity func() daemoncontrol.Identity
}

// NewHealthHandler creates a new daemon health handler.
func NewHealthHandler(identity ...func() daemoncontrol.Identity) gin.HandlerFunc {
	return (&HealthHandler{identity: firstIdentity(identity)}).Handle
}

// Handle returns a lightweight JSON payload suitable for local health checks.
func (h *HealthHandler) Handle(c *gin.Context) {
	payload := gin.H{
		"ok":  true,
		"pid": os.Getpid(),
	}
	if h.identity != nil {
		identity := h.identity()
		payload["instanceId"] = identity.InstanceID
		payload["desktopApiVersion"] = identity.DesktopAPIVersion
		payload["draining"] = identity.Draining
	}
	c.JSON(http.StatusOK, payload)
}

func firstIdentity(values []func() daemoncontrol.Identity) func() daemoncontrol.Identity {
	if len(values) == 0 {
		return nil
	}
	return values[0]
}
