package javadocs

import (
	"strings"
	"testing"

	"github.com/PuerkitoBio/goquery"
)

const testPackagePageHTML = `
<!DOCTYPE html>
<html>
<body>
<h1>Package java.util</h1>
<div class="block">Contains the collections framework, legacy collection classes, event model, date and time facilities.</div>

<table class="type-summary">
<tr>
<td><a href="ArrayList.html">ArrayList</a></td>
<td>Resizable-array implementation of the List interface.</td>
</tr>
<tr>
<td><a href="HashMap.html">HashMap</a></td>
<td>Hash table based implementation of the Map interface.</td>
</tr>
</table>

<table class="interface-summary">
<tr>
<td><a href="List.html">List</a></td>
<td>An ordered collection (also known as a sequence).</td>
</tr>
</table>

<table class="exception-summary">
<tr>
<td><a href="ConcurrentModificationException.html">ConcurrentModificationException</a></td>
<td>This exception may be thrown by methods that detect concurrent modification.</td>
</tr>
</table>
</body>
</html>
`

func TestParsePackagePage(t *testing.T) {
	parser := NewParser()
	pkg, err := parser.ParsePackagePage(testPackagePageHTML, "https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/package-summary.html")
	if err != nil {
		t.Fatalf("ParsePackagePage failed: %v", err)
	}

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

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

	if len(pkg.Classes) == 0 {
		t.Error("Expected at least one class")
	}

	if len(pkg.Interfaces) == 0 {
		t.Error("Expected at least one interface")
	}

	if len(pkg.Exceptions) == 0 {
		t.Error("Expected at least one exception")
	}
}

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

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

	classes := parser.extractClasses(doc, "java.util", "https://docs.oracle.com/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")
	}

	if first.Package != "java.util" {
		t.Errorf("Expected package 'java.util', got %q", first.Package)
	}
}

func TestResolveURL(t *testing.T) {
	tests := []struct {
		base     string
		href     string
		expected string
	}{
		{"https://docs.oracle.com", "/api/ArrayList.html", "https://docs.oracle.com/api/ArrayList.html"},
		{"https://docs.oracle.com", "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)
			}
		})
	}
}
