package mcp

import (
	"context"
	"strings"
	"testing"

	"github.com/modelcontextprotocol/go-sdk/mcp"
)

// sprintResult extracts the concatenated text content from a tool result.
func sprintResult(r *mcp.CallToolResult) string {
	var b strings.Builder
	for _, c := range r.Content {
		if tc, ok := c.(*mcp.TextContent); ok {
			b.WriteString(tc.Text)
		}
	}
	return b.String()
}

func TestSanitizeBodyStripsHTML(t *testing.T) {
	raw := `<html><head><style>.x{color:red}</style><script>alert(1)</script></head>` +
		`<body><h1>Hello &amp; Welcome</h1><p>Deploy with docker compose up -d</p></body></html>`
	out := sanitizeBody("text/html; charset=utf-8", raw)
	if strings.Contains(out, "<script") || strings.Contains(out, "alert(1)") {
		t.Errorf("script not stripped: %q", out)
	}
	if strings.Contains(out, ".x{color:red}") {
		t.Errorf("style not stripped: %q", out)
	}
	if !strings.Contains(out, "Hello & Welcome") {
		t.Errorf("expected unescaped heading text, got: %q", out)
	}
	if !strings.Contains(out, "docker compose up -d") {
		t.Errorf("expected body text preserved, got: %q", out)
	}
}

func TestHTTPGetBlocksPrivateAndBadScheme(t *testing.T) {
	cases := []string{
		"http://127.0.0.1:8080/",
		"http://localhost/admin",
		"http://192.168.8.77/",
		"http://10.0.0.5/",
		"file:///etc/passwd",
		"ftp://example.com/x",
		"",
	}
	for _, c := range cases {
		out := sprintResult(httpGet(context.Background(), c))
		if !strings.Contains(strings.ToLower(out), "error") && !strings.Contains(strings.ToLower(out), "refus") {
			t.Errorf("%q: expected rejection, got %q", c, out)
		}
	}
}
