package springdocs

import (
	"strings"
	"testing"

	"github.com/PuerkitoBio/goquery"
)

const testModulePageHTML = `
<!DOCTYPE html>
<html>
<body>
<h1>Spring Boot Reference</h1>
<p class="lead">Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications.</p>

<table class="table">
<tbody>
<tr>
<td><a href="/spring-boot/docs/current/api/org/springframework/boot/SpringApplication.html">SpringApplication</a></td>
<td>Class used to bootstrap and launch a Spring application.</td>
</tr>
</tbody>
</table>

<div class="configuration-property">
<dt><code>server.port</code></dt>
<dd>Server HTTP port.</dd>
</div>
</body>
</html>
`

func TestParseModulePage(t *testing.T) {
	parser := NewParser()
	module, err := parser.ParseModulePage(testModulePageHTML, "https://docs.spring.io/spring-boot/docs/current/reference/html/")
	if err != nil {
		t.Fatalf("ParseModulePage failed: %v", err)
	}

	if module.Name == "" {
		t.Error("Expected non-empty module name")
	}

	if module.Doc == "" {
		t.Error("Expected non-empty doc")
	}
}

func TestExtractClasses(t *testing.T) {
	parser := NewParser()

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(testModulePageHTML))
	if err != nil {
		t.Fatalf("Failed to parse HTML: %v", err)
	}

	classes := parser.extractClasses(doc, "spring-boot", "https://docs.spring.io/test")

	if len(classes) == 0 {
		t.Fatal("Expected at least one class")
	}

	first := classes[0]
	if first.Name == "" {
		t.Error("Expected non-empty class name")
	}
}

func TestExtractProperties(t *testing.T) {
	parser := NewParser()

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(testModulePageHTML))
	if err != nil {
		t.Fatalf("Failed to parse HTML: %v", err)
	}

	props := parser.extractProperties(doc, "https://docs.spring.io/test")

	if len(props) == 0 {
		t.Skip("No properties extracted from test HTML")
	}
}

func TestResolveURL(t *testing.T) {
	tests := []struct {
		base     string
		href     string
		expected string
	}{
		{"https://docs.spring.io", "/api/TestClass.html", "https://docs.spring.io/api/TestClass.html"},
		{"https://docs.spring.io", "https://example.com/page", "https://example.com/page"},
	}

	for _, tt := range tests {
		t.Run(tt.href, func(t *testing.T) {
			got := resolveURL(tt.base, tt.href)
			if got != tt.expected {
				t.Errorf("resolveURL(%q, %q) = %q, want %q", tt.base, tt.href, got, tt.expected)
			}
		})
	}
}
