package nuxtdocs

import (
	"strings"
	"testing"

	"github.com/PuerkitoBio/goquery"
)

const testReferencePageHTML = `
<!DOCTYPE html>
<html>
<body>
<h1>Nuxt API Reference</h1>

<h2 id="useFetch">useFetch</h2>
<p>Fetches data from an API endpoint with SSR support.</p>
<pre><code>const { data, pending, error } = await useFetch('/api/data')</code></pre>

<h2 id="useState">useState</h2>
<p>Creates a reactive state that is shared across components.</p>

<h2 id="NuxtPage">NuxtPage</h2>
<p>Renders the current page component based on the route.</p>

<h2 id="server">server</h2>
<p>Nuxt server configuration options.</p>

<h3 id="nuxi-dev">nuxi dev</h3>
<p>Starts the development server.</p>
</body>
</html>
`

func TestParseReferencePage(t *testing.T) {
	parser := NewParser()
	ref, err := parser.ParseReferencePage(testReferencePageHTML, "https://nuxt.com/docs/api/")
	if err != nil {
		t.Fatalf("ParseReferencePage failed: %v", err)
	}

	if len(ref.Composables) == 0 {
		t.Error("Expected at least one composable")
	}

	if len(ref.Components) == 0 {
		t.Error("Expected at least one component")
	}

	if len(ref.Commands) == 0 {
		t.Error("Expected at least one command")
	}
}

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

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

	composables := parser.extractComposables(doc, "https://nuxt.com/docs/api/")

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

	found := false
	for _, c := range composables {
		if c.Name == "useFetch" {
			found = true
			if c.Doc == "" {
				t.Error("Expected useFetch to have documentation")
			}
			break
		}
	}

	if !found {
		t.Error("Expected to find useFetch composable")
	}
}

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

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

	components := parser.extractComponents(doc, "https://nuxt.com/docs/api/")

	found := false
	for _, c := range components {
		if c.Name == "NuxtPage" {
			found = true
			break
		}
	}

	if !found {
		t.Error("Expected to find NuxtPage component")
	}
}

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