package system

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

	"github.com/gin-gonic/gin"
	"github.com/stretchr/testify/require"

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

func TestHealthHandlerReturnsOK(t *testing.T) {
	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.GET("/api/health", NewHealthHandler())

	req := httptest.NewRequest(http.MethodGet, "/api/health", nil)
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)

	require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())

	var body struct {
		OK  bool `json:"ok"`
		PID int  `json:"pid"`
	}
	require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &body))
	require.True(t, body.OK)
	require.Positive(t, body.PID)
}

func TestHealthHandlerReturnsOnlyPublicCompatibilityFacts(t *testing.T) {
	gin.SetMode(gin.TestMode)
	router := gin.New()
	router.GET("/api/health", NewHealthHandler(func() daemoncontrol.Identity {
		return daemoncontrol.Identity{
			InstanceID:        "instance-health",
			DesktopAPIVersion: 3,
			OwnerKind:         daemoncontrol.OwnerKindElectron,
			Draining:          true,
		}
	}))

	req := httptest.NewRequest(http.MethodGet, "/api/health", nil)
	rec := httptest.NewRecorder()
	router.ServeHTTP(rec, req)

	require.Equal(t, http.StatusOK, rec.Code)
	require.JSONEq(t, `{
		"ok": true,
		"pid": `+fmt.Sprint(os.Getpid())+`,
		"instanceId": "instance-health",
		"desktopApiVersion": 3,
		"draining": true
	}`, rec.Body.String())
	require.NotContains(t, rec.Body.String(), "owner")
	require.NotContains(t, rec.Body.String(), "token")
}
