package mcp

import (
	"context"
	"encoding/json"
	"fmt"
	"testing"

	"github.com/mark3labs/mcp-go/mcp"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	worktree "github.com/aki/amux/internal/worktree"
)

func TestHandleWorkspaceListResource(t *testing.T) {
	s := setupTestServer(t)

	// Create a test workspace
	ws, err := s.worktreeManager.Create(context.Background(), worktree.CreateOptions{
		Name:        "test-workspace",
		Description: "Test workspace for resource testing",
	})
	require.NoError(t, err)

	ctx := context.Background()
	request := mcp.ReadResourceRequest{
		Params: mcp.ReadResourceParams{
			URI: "amux://worktree",
		},
	}

	contents, err := s.handleWorktreeListResource(ctx, request)
	require.NoError(t, err)
	require.Len(t, contents, 1)

	textContent, ok := contents[0].(*mcp.TextResourceContents)
	require.True(t, ok)
	assert.Equal(t, "amux://worktree", textContent.URI)
	assert.Equal(t, "application/json", textContent.MIMEType)

	// Parse the JSON to verify structure
	var workspaces []map[string]interface{}
	err = json.Unmarshal([]byte(textContent.Text), &workspaces)
	require.NoError(t, err)
	require.GreaterOrEqual(t, len(workspaces), 1)

	// Find our test workspace
	found := false
	for _, w := range workspaces {
		if w["id"] == ws.Branch {
			found = true
			assert.Equal(t, ws.Branch, w["name"]) // Name is now same as Branch
			assert.Equal(t, "Test workspace for resource testing", w["description"])

			// Check resources are included
			resources, ok := w["resources"].(map[string]interface{})
			require.True(t, ok, "resources field should be present")
			assert.Equal(t, fmt.Sprintf("amux://worktree/%s", ws.Branch), resources["detail"])
			assert.Equal(t, fmt.Sprintf("amux://worktree/%s/files", ws.Branch), resources["files"])
			break
		}
	}
	assert.True(t, found, "Test workspace not found in list")
}

func TestRegisterResources(t *testing.T) {
	s := setupTestServer(t)

	// Test that registerResources completes without error
	// Since MCPServer doesn't expose ListResources method,
	// we'll test by attempting to read the resources

	// Test worktree list resource
	ctx := context.Background()
	workspaceReq := mcp.ReadResourceRequest{
		Params: mcp.ReadResourceParams{
			URI: "amux://worktree",
		},
	}
	contents, err := s.handleWorktreeListResource(ctx, workspaceReq)
	require.NoError(t, err)
	assert.NotEmpty(t, contents)
}
