package exec

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"

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

	"github.com/tidbcloud/AgentTeam/desktop/internal/agentview"
	"github.com/tidbcloud/AgentTeam/desktop/internal/token"
	"github.com/tidbcloud/AgentTeam/desktop/internal/wire/apiclient"
)

func TestAgentRoutesUseInjectedSource(t *testing.T) {
	gin.SetMode(gin.TestMode)
	keys, err := token.NewKeyManager(t.TempDir() + "/config.yaml")
	require.NoError(t, err)
	authorizations := NewRuntimeAuthorizationStore(keys)
	lease, err := authorizations.Create(RuntimeAuthorizationConfig{
		ServerID: "server-1", AgentID: "agent-1", SessionID: "session-1", RunID: "run-1",
		WorkDir: t.TempDir(), Server: &apiclient.Client{},
		ContextExpires: time.Now().Add(time.Hour), TokenTTL: time.Hour,
	})
	require.NoError(t, err)

	source := fakeAgentReader{items: []agentview.Snapshot{
		{ID: "agent-alpha", Name: "Alpha", Runtime: "builtin", Status: "ready"},
		{ID: "agent-beta", Name: "Beta", Runtime: "codex", Status: "active"},
	}}
	router := gin.New()
	RegisterRoutes(router.Group("/api/internal/exec"), RouteDependencies{Authorizations: authorizations, Agents: source})

	list := execAgentRouteRequest(t, router, lease.Token, "list", `{"query":"beta","limit":1}`)
	require.Equal(t, http.StatusOK, list.Code)
	require.JSONEq(t, `{"data":{"agents":[{"id":"agent-beta","name":"Beta","runtime":"codex","status":"active","backendRegistered":false}],"hasMore":false},"text":"Listed agents."}`, list.Body.String())

	get := execAgentRouteRequest(t, router, lease.Token, "get", `{"agentId":"agent-alpha"}`)
	require.Equal(t, http.StatusOK, get.Code)
	require.Contains(t, get.Body.String(), `"id":"agent-alpha"`)

	missing := execAgentRouteRequest(t, router, lease.Token, "get", `{"agentId":"missing"}`)
	require.Equal(t, http.StatusNotFound, missing.Code)
}

func execAgentRouteRequest(t *testing.T, router http.Handler, tokenValue, action, body string) *httptest.ResponseRecorder {
	t.Helper()
	request := httptest.NewRequest(
		http.MethodPost,
		"/api/internal/exec/servers/server-1/agents/agent-1/agent/"+action,
		strings.NewReader(body),
	)
	request.Header.Set("Authorization", "Bearer "+tokenValue)
	response := httptest.NewRecorder()
	router.ServeHTTP(execDeadlineRecorder{ResponseRecorder: response}, request)
	return response
}

type execDeadlineRecorder struct{ *httptest.ResponseRecorder }

func (execDeadlineRecorder) SetReadDeadline(time.Time) error { return nil }

var _ AgentReader = fakeAgentReader{}
