package sponsoredads

import (
	"encoding/xml"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

const defaultFeedBaseURL = "http://xml.admedia.com/xml.php"

// SearchParams are the inputs for an AdMedia sponsored XML feed request.
type SearchParams struct {
	AffID    string
	Keywords string
	SubID    string
	FeedURL  string // optional full URL override (tests)
	IP       string
	RPP      int
	UA       string
	Referral string
	OOS      string
}

// Listing is a single sponsored ad entry from the XML feed.
type Listing struct {
	Title       string `json:"title"`
	Redirect    string `json:"redirect"`
	URL         string `json:"url"`
	Description string `json:"description"`
}

type xmlListing struct {
	Title       string `xml:"title"`
	Redirect    string `xml:"redirect"`
	URL         string `xml:"url"`
	Description string `xml:"description"`
}

// AdMedia wraps listings in <dsxout><results><listing>…</listing></results></dsxout>.
type xmlDSXOutResponse struct {
	XMLName xml.Name        `xml:"dsxout"`
	Results xmlResultsBlock `xml:"results"`
}

type xmlResultsRootResponse struct {
	XMLName  xml.Name     `xml:"results"`
	Listings []xmlListing `xml:"listing"`
}

type xmlResultsBlock struct {
	Listings []xmlListing `xml:"listing"`
}

// Client fetches and parses sponsored ad XML feeds.
type Client struct {
	httpClient *http.Client
	baseURL    string
}

func NewClient(baseURL string) *Client {
	if baseURL == "" {
		baseURL = defaultFeedBaseURL
	}
	return &Client{
		httpClient: &http.Client{Timeout: 10 * time.Second},
		baseURL:    baseURL,
	}
}

func (c *Client) buildFeedURL(p SearchParams) (string, error) {
	if p.FeedURL != "" {
		return p.FeedURL, nil
	}
	if p.AffID == "" || p.Keywords == "" {
		return "", fmt.Errorf("affiliate id and keywords are required")
	}

	subID := p.SubID
	if subID == "" {
		subID = "items.com"
	}
	rpp := p.RPP
	if rpp <= 0 {
		rpp = 5
	}

	u, err := url.Parse(c.baseURL)
	if err != nil {
		return "", fmt.Errorf("invalid feed base URL: %w", err)
	}

	q := u.Query()
	q.Set("affiliate", p.AffID)
	q.Set("subid", subID)
	q.Set("Terms", p.Keywords)
	if p.IP != "" {
		q.Set("IP", p.IP)
	}
	q.Set("rpp", strconv.Itoa(rpp))
	q.Set("ua", p.UA)
	q.Set("ref", p.Referral)
	if p.OOS != "" {
		q.Set("oos", p.OOS)
	}
	u.RawQuery = q.Encode()

	return u.String(), nil
}

// Search fetches the XML feed and returns deduplicated listings by title.
func (c *Client) Search(p SearchParams) ([]Listing, error) {
	feedURL, err := c.buildFeedURL(p)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest(http.MethodGet, feedURL, nil)
	if err != nil {
		return nil, err
	}
	if p.IP != "" {
		req.Header.Set("X-Forwarded-For", p.IP)
	}

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("feed returned status %d", resp.StatusCode)
	}

	body, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
	if err != nil {
		return nil, err
	}
	return parseListings(body)
}

func parseListings(body []byte) ([]Listing, error) {
	if len(body) == 0 {
		return []Listing{}, nil
	}

	var dsx xmlDSXOutResponse
	if err := xml.Unmarshal(body, &dsx); err == nil && len(dsx.Results.Listings) > 0 {
		return dedupeListings(dsx.Results.Listings), nil
	}

	var root xmlResultsRootResponse
	if err := xml.Unmarshal(body, &root); err != nil {
		return []Listing{}, nil
	}

	return dedupeListings(root.Listings), nil
}

func dedupeListings(raw []xmlListing) []Listing {
	seen := make(map[string]bool, len(raw))
	out := make([]Listing, 0, len(raw))

	for _, item := range raw {
		title := strings.TrimSpace(item.Title)
		if title == "" || seen[title] {
			continue
		}
		seen[title] = true
		out = append(out, Listing{
			Title:       title,
			Redirect:    strings.TrimSpace(item.Redirect),
			URL:         strings.TrimSpace(item.URL),
			Description: strings.TrimSpace(item.Description),
		})
	}

	return out
}
