package sponsoredads

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"
)

const sampleXML = `<?xml version="1.0"?>
<results>
  <listing>
    <title>First Ad Title</title>
    <redirect>https://click.example/1</redirect>
    <url>https://www.example.com/page1</url>
    <description>First ad description</description>
  </listing>
  <listing>
    <title>First Ad Title</title>
    <redirect>https://click.example/1-dup</redirect>
    <url>https://www.example.com/page1-dup</url>
    <description>Duplicate title should be skipped</description>
  </listing>
  <listing>
    <title>Second Ad Title</title>
    <redirect>https://click.example/2</redirect>
    <url>https://www.example.com/page2</url>
    <description>Second ad description</description>
  </listing>
</results>`

const sampleDSXOutXML = `<dsxout>
<results>
  <listing>
    <title>Best Deals On Video Games</title>
    <description>Great Dryer Deals</description>
    <redirect>http://click.example/1</redirect>
    <url>https://www.bestbuy.com/TopDeals</url>
  </listing>
  <listing>
    <title>Earn Instant Cash Back From Your Computer</title>
    <description>Items Bring You the Joy of Exciting Cash Back.</description>
    <redirect>http://click.example/2</redirect>
    <url>www.items.com</url>
  </listing>
</results>
</dsxout>`

func TestSearch_ForwardsClientIPHeader(t *testing.T) {
	var gotIP string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		gotIP = r.Header.Get("X-Forwarded-For")
		w.Header().Set("Content-Type", "application/xml")
		w.Write([]byte(sampleDSXOutXML))
	}))
	defer srv.Close()

	client := NewClient("")
	_, err := client.Search(SearchParams{
		AffID:    "test-aff",
		Keywords: "bestbuy",
		IP:       "203.0.113.10",
		FeedURL:  srv.URL,
	})
	if err != nil {
		t.Fatalf("Search() error = %v", err)
	}
	if gotIP != "203.0.113.10" {
		t.Fatalf("X-Forwarded-For header = %q, want 203.0.113.10", gotIP)
	}
}

func TestSearch_ParsesDSXOutFeed(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/xml")
		w.Write([]byte(sampleDSXOutXML))
	}))
	defer srv.Close()

	client := NewClient("")
	listings, err := client.Search(SearchParams{
		AffID:    "pointwines",
		Keywords: "bestbuy",
		FeedURL:  srv.URL,
	})
	if err != nil {
		t.Fatalf("Search() error = %v", err)
	}
	if len(listings) != 2 {
		t.Fatalf("len(listings) = %d, want 2", len(listings))
	}
}

func TestSearch_ParsesAndDedupesListings(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/xml")
		w.Write([]byte(sampleXML))
	}))
	defer srv.Close()

	client := NewClient("")
	listings, err := client.Search(SearchParams{
		AffID:    "test-aff",
		Keywords: "health fitness",
		SubID:    "bodytheory.com",
		IP:       "127.0.0.1",
		RPP:      5,
		UA:       "test-agent",
		Referral: "https://bodytheory.com/",
		OOS:      "https://bodytheory.com/",
		FeedURL:  srv.URL,
	})
	if err != nil {
		t.Fatalf("Search() error = %v", err)
	}
	if len(listings) != 2 {
		t.Fatalf("len(listings) = %d, want 2", len(listings))
	}
	if listings[0].Title != "First Ad Title" || listings[1].Title != "Second Ad Title" {
		t.Fatalf("unexpected listings: %+v", listings)
	}
}

func TestSearch_EmptyBodyReturnsEmptySlice(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	}))
	defer srv.Close()

	client := NewClient("")
	listings, err := client.Search(SearchParams{
		AffID:    "test-aff",
		Keywords: "health",
		FeedURL:  srv.URL,
	})
	if err != nil {
		t.Fatalf("Search() error = %v", err)
	}
	if len(listings) != 0 {
		t.Fatalf("len(listings) = %d, want 0", len(listings))
	}
}

func TestSearch_InvalidXMLReturnsEmptySlice(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("not xml"))
	}))
	defer srv.Close()

	client := NewClient("")
	listings, err := client.Search(SearchParams{
		AffID:    "test-aff",
		Keywords: "health",
		FeedURL:  srv.URL,
	})
	if err != nil {
		t.Fatalf("Search() error = %v", err)
	}
	if len(listings) != 0 {
		t.Fatalf("len(listings) = %d, want 0", len(listings))
	}
}

func TestBuildFeedURL_SetsQueryParams(t *testing.T) {
	client := NewClient(defaultFeedBaseURL)
	rawURL, err := client.buildFeedURL(SearchParams{
		AffID:    "aff123",
		Keywords: "wine",
		SubID:    "pointwines.com",
		IP:       "1.2.3.4",
		RPP:      3,
		UA:       "Mozilla",
		Referral: "https://pointwines.com/",
		OOS:      "https://pointwines.com/",
	})
	if err != nil {
		t.Fatalf("buildFeedURL() error = %v", err)
	}

	parsed, err := url.Parse(rawURL)
	if err != nil {
		t.Fatalf("url.Parse() error = %v", err)
	}

	q := parsed.Query()
	checks := map[string]string{
		"affiliate": "aff123",
		"subid":     "pointwines.com",
		"Terms":     "wine",
		"IP":        "1.2.3.4",
		"rpp":       "3",
		"ua":        "Mozilla",
		"ref":       "https://pointwines.com/",
		"type":      "4",
		"oos":       "https://pointwines.com/",
	}
	for key, want := range checks {
		if got := q.Get(key); got != want {
			t.Errorf("query[%q] = %q, want %q", key, got, want)
		}
	}
}
