package webagent

import (
	"net/http"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/api/daemon"
	"github.com/tidbcloud/AgentTeam/internal/api/testkit/httputil"
	"github.com/tidbcloud/AgentTeam/internal/store/agent"
)

func TestMemorySyncHandlersReadDaemonLocalState(t *testing.T) {
	fake := newFakeStore()
	fake.runtimeSnapshots = []agent.AgentRuntimeSnapshot{{AgentID: "agt_1", MachineID: "mach_1", CanManage: true}}
	runtime := &fakeRuntime{
		memorySyncKnown: true,
		memorySyncStatus: daemon.AgentMemorySyncStatus{
			State:  "pending_sync",
			Reason: "push_failed",
		},
		memoryRetryOK: true,
	}
	router := newWebAgentRouter(Dependencies{AgentStore: fake, ReviewStore: fake, Runtime: runtime})

	response := httputil.DoJSON(t, router, http.MethodGet, "/api/v1/workspaces/wsp_1/agents/agt_1/memory-sync", nil)
	require.Equal(t, http.StatusOK, response.Code)
	require.JSONEq(t, `{"state":"pending_sync","reason":"push_failed"}`, response.Body.String())
	require.Equal(t, agentCall{MachineID: "mach_1", AgentID: "agt_1"}, runtime.lastMemorySync)

	response = httputil.DoJSON(t, router, http.MethodPost, "/api/v1/workspaces/wsp_1/agents/agt_1/memory-sync/retry", nil)
	require.Equal(t, http.StatusAccepted, response.Code)
	require.JSONEq(t, `{"retryRequested":true}`, response.Body.String())
}

func TestMemorySyncStatusDistinguishesMissingAndUnsupportedRuntimeState(t *testing.T) {
	fake := newFakeStore()
	fake.runtimeSnapshots = []agent.AgentRuntimeSnapshot{{AgentID: "agt_1", MachineID: "mach_1", CanManage: true}}
	runtime := &fakeRuntime{}
	router := newWebAgentRouter(Dependencies{AgentStore: fake, ReviewStore: fake, Runtime: runtime})

	response := httputil.DoJSON(t, router, http.MethodGet, "/api/v1/workspaces/wsp_1/agents/agt_1/memory-sync", nil)
	require.Equal(t, http.StatusNotFound, response.Code)

	runtime.memorySyncErr = daemon.ErrMemorySyncEndpointUnsupported
	response = httputil.DoJSON(t, router, http.MethodGet, "/api/v1/workspaces/wsp_1/agents/agt_1/memory-sync", nil)
	require.Equal(t, http.StatusNotImplemented, response.Code)
}

func TestMemorySyncHandlersRequireAgentWorkspaceReadAccess(t *testing.T) {
	fake := newFakeStore()
	fake.runtimeSnapshots = []agent.AgentRuntimeSnapshot{{AgentID: "agt_1", MachineID: "mach_1", CanManage: false}}
	runtime := &fakeRuntime{memorySyncKnown: true}
	router := newWebAgentRouter(Dependencies{AgentStore: fake, ReviewStore: fake, Runtime: runtime})

	response := httputil.DoJSON(t, router, http.MethodGet, "/api/v1/workspaces/wsp_1/agents/agt_1/memory-sync", nil)
	require.Equal(t, http.StatusForbidden, response.Code)
	require.Empty(t, runtime.lastMemorySync)
}
