package tsdocs

import (
	"strings"
	"testing"

	"github.com/PuerkitoBio/goquery"
)

const testModulePageHTML = `
<!DOCTYPE html>
<html>
<body>
<h1>TypeScript Handbook</h1>
<p class="content">TypeScript is a strongly typed programming language that builds on JavaScript.</p>

<h2 id="string">interface String</h2>
<p>Allows manipulation and formatting of text strings.</p>

<h3 id="concat">concat(...strings: string[]): string</h3>
<p>Returns a string that contains the concatenation of two or more strings.</p>

<h2 id="Array">interface Array&lt;T&gt;</h2>
<p>An array of values.</p>

<pre><code>function identity<T>(arg: T): T {
  return arg;
}</code></pre>
</body>
</html>
`

func TestParseModulePage(t *testing.T) {
	parser := NewParser()
	module, err := parser.ParseModulePage(testModulePageHTML, "https://www.typescriptlang.org/docs/handbook/")
	if err != nil {
		t.Fatalf("ParseModulePage failed: %v", err)
	}

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

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

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

	interfaces := parser.extractInterfaces(doc, "typescript", "https://www.typescriptlang.org/docs/test")

	for _, iface := range interfaces {
		if iface.Name == "interface" {
			t.Error("Should not include 'interface' as a name")
		}
	}
}

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

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

	functions := parser.extractFunctions(doc, "typescript", "https://www.typescriptlang.org/docs/test")

	for _, fn := range functions {
		if fn.Name != "" && fn.Signature != "" {
			return
		}
	}
}

func TestResolveURL(t *testing.T) {
	tests := []struct {
		base     string
		href     string
		expected string
	}{
		{"https://www.typescriptlang.org", "/docs/handbook", "https://www.typescriptlang.org/docs/handbook"},
		{"https://www.typescriptlang.org", "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)
			}
		})
	}
}
