package services

import (
	"encoding/xml"
	"net/url"
	"strings"
	"testing"

	"golang.org/x/net/html"
)

func TestSitemapDecode(t *testing.T) {
	var us sitemapDoc
	if err := xml.Unmarshal([]byte(`<urlset><url><loc>https://x.com/a</loc></url><url><loc>https://x.com/b</loc></url></urlset>`), &us); err != nil {
		t.Fatal(err)
	}
	if len(us.URLs) != 2 || us.URLs[0].Loc != "https://x.com/a" {
		t.Errorf("urlset decode salah: %+v", us.URLs)
	}
	var idx sitemapDoc
	if err := xml.Unmarshal([]byte(`<sitemapindex><sitemap><loc>https://x.com/sm1.xml</loc></sitemap></sitemapindex>`), &idx); err != nil {
		t.Fatal(err)
	}
	if len(idx.Sitemaps) != 1 || idx.Sitemaps[0].Loc != "https://x.com/sm1.xml" {
		t.Errorf("sitemapindex decode salah: %+v", idx.Sitemaps)
	}
}

func TestChunkText(t *testing.T) {
	if ChunkText("   ") != nil {
		t.Error("teks kosong harus nil")
	}
	if got := ChunkText("halo dunia"); len(got) != 1 || got[0] != "halo dunia" {
		t.Errorf("teks pendek harus 1 chunk utuh, dapat %v", got)
	}
	long := strings.Repeat("a", chunkSize*2+50)
	got := ChunkText(long)
	if len(got) < 2 {
		t.Fatalf("teks panjang harus terpecah >1 chunk, dapat %d", len(got))
	}
	// Tiap chunk tidak melebihi ukuran maksimum.
	for i, c := range got {
		if len([]rune(c)) > chunkSize {
			t.Errorf("chunk %d melebihi %d rune (%d)", i, chunkSize, len([]rune(c)))
		}
	}
}

func TestNormalizeURL(t *testing.T) {
	cases := map[string]string{
		"https://x.com/a/?q=1#frag": "https://x.com/a/?q=1",
		"https://x.com/a/":          "https://x.com/a",
		"http://x.com":              "http://x.com",
		"ftp://x.com/file":          "", // skema tidak didukung
		"/relatif":                  "", // tanpa host
	}
	for in, want := range cases {
		if got := normalizeURL(in); got != want {
			t.Errorf("normalizeURL(%q) = %q, mau %q", in, got, want)
		}
	}
}

func TestCanonicalHost(t *testing.T) {
	for in, want := range map[string]string{
		"www.Toko.com":   "toko.com",
		"toko.com:8080":  "toko.com",
		"WWW.toko.co.id": "toko.co.id",
	} {
		if got := canonicalHost(in); got != want {
			t.Errorf("canonicalHost(%q) = %q, mau %q", in, got, want)
		}
	}
}

func TestExtractTitleText(t *testing.T) {
	doc, _ := html.Parse(strings.NewReader(`
		<html><head><title>Toko Kaos</title><style>.x{color:red}</style></head>
		<body><h1>Promo</h1><p>Diskon 20%</p><script>alert('x')</script></body></html>`))
	title, text := extractTitleText(doc)
	if title != "Toko Kaos" {
		t.Errorf("title = %q, mau \"Toko Kaos\"", title)
	}
	if !strings.Contains(text, "Promo") || !strings.Contains(text, "Diskon 20%") {
		t.Errorf("text harus berisi konten body, dapat %q", text)
	}
	if strings.Contains(text, "alert") || strings.Contains(text, "color:red") {
		t.Errorf("text tidak boleh memuat isi script/style, dapat %q", text)
	}
}

// Proteksi email Cloudflare: atribut data-cfemail harus didekode dan placeholder "[email protected]"
// tidak boleh ikut ke teks hasil crawl (pernah membuat 4 item pengetahuan memuat alamat palsu).
func TestExtractTitleTextDecodesCloudflareEmail(t *testing.T) {
	// Fixture heksadesimal ini didekode menjadi ngertikode.id@gmail.com.
	htmlSumber := `<html><head><title>Kontak</title></head><body>
		<p>Hubungi kami: Email <a href="/cdn-cgi/l/email-protection#5f31383a2d2b3634303b3a71363b1f38323e3633713c3032" data-cfemail="5f31383a2d2b3634303b3a71363b1f38323e3633713c3032">[email protected]</a> WhatsApp +62 813-2594-224</p>
		<p>Sisa placeholder tanpa atribut: [email protected]</p></body></html>`
	doc, err := html.Parse(strings.NewReader(htmlSumber))
	if err != nil {
		t.Fatal(err)
	}
	_, text := extractTitleText(doc)
	if !strings.Contains(text, "ngertikode.id@gmail.com") {
		t.Errorf("alamat asli tidak muncul di teks crawl: %q", text)
	}
	if strings.Contains(text, "[email protected]") {
		t.Errorf("placeholder email masih ikut tertext: %q", text)
	}
	if !strings.Contains(text, "+62 813-2594-224") {
		t.Errorf("teks lain di sekitar email hilang: %q", text)
	}
}

func TestCloudflareEmailAddressRejectsBadInput(t *testing.T) {
	for _, tc := range []struct{ nama, attr string }{
		{"heksadesimal tidak valid", "zzzz"},
		{"terlalu pendek", "5f"},
		{"hasil bukan email", "5f3132"},
	} {
		t.Run(tc.nama, func(t *testing.T) {
			n := &html.Node{Type: html.ElementNode, Data: "a", Attr: []html.Attribute{{Key: "data-cfemail", Val: tc.attr}}}
			if alamat, ok := cloudflareEmailAddress(n); ok {
				t.Fatalf("masukan tidak valid diterima: %q", alamat)
			}
		})
	}
}

func TestExtractLinks(t *testing.T) {
	base, _ := url.Parse("https://toko.com/produk")
	doc, _ := html.Parse(strings.NewReader(
		`<a href="/kontak">k</a><a href="https://toko.com/about">a</a><a href="https://lain.com/x">x</a>`))
	links := extractLinks(doc, base)
	joined := strings.Join(links, " ")
	if !strings.Contains(joined, "https://toko.com/kontak") {
		t.Errorf("link relatif harus di-resolve absolut, dapat %v", links)
	}
	if !strings.Contains(joined, "https://toko.com/about") {
		t.Errorf("link absolut hilang, dapat %v", links)
	}
}
