package routes

import (
	"log"
	"net/http"
	"reflect"
	"sync"
	"sync/atomic"
	"time"

	"bitbucket.org/imediabrands/oos-service/middlewares"
)

// articleBelongsToSite reports whether an article may be served as the
// requested site's. The CMS has no site field on an article and every site
// shares its article IDs, so without this check any site would serve another
// site's article under its own domain. An article is the site's when:
//   - its CMS category is one of the site's categories or subcategories and
//     no other site's (a name like "Articles" or "Blog" is many sites');
//   - its category is no site's at all (e.g. one created since the categories
//     were cached), so it can't be another site's;
//   - or the site's own category listings include it: an article filed under
//     another site's category name, or under a name the site shares.
//
// When the CMS can't tell (a failed request, or a site it doesn't list) the
// article counts as the site's, as in categoryRouteMissing.
func articleBelongsToSite(req *http.Request, category, articleID string) bool {
	response, err := loadCMSCategories()
	if err != nil {
		log.Printf("[ERROR] articleBelongsToSite: categories: %v", err)
		return true
	}
	domain := middlewares.ResolveToProductionDomain(requestPublicHost(req))
	data, _ := response["data"].(map[string]interface{})
	if _, listed := domainCategories(data, domain); !listed {
		return true
	}

	slug := slugify(category)
	sites := cmsCategorySlugs(response)[slug]
	if slug == "" || sites == 0 {
		return true
	}
	if sites == 1 && siteHasCategorySlug(response, domain, slug) {
		return true
	}

	listed, err := siteListsArticle(domain, articleID)
	if err != nil {
		log.Printf("[ERROR] articleBelongsToSite: articles: %v", err)
		return true
	}
	return listed
}

// siteHasCategorySlug reports whether slug is one of the domain's category or
// subcategory slugs.
func siteHasCategorySlug(response map[string]interface{}, domain, slug string) bool {
	for _, c := range extractSitemapCategories(response, domain) {
		if c.Slug == slug {
			return true
		}
		for _, sub := range c.Subcategories {
			if sub.Slug == slug {
				return true
			}
		}
	}
	return false
}

// cmsCategorySlugIndex counts, for every category and subcategory slug in one
// parsed getcategories response, the sites that have it.
type cmsCategorySlugIndex struct {
	// response is held (not just its address) so its address can't be reused
	// by a later response while this index is current.
	response map[string]interface{}
	slugs    map[string]int
}

var lastCategorySlugIndex atomic.Pointer[cmsCategorySlugIndex]

// cmsCategorySlugs returns every category and subcategory slug of every site in
// response with the number of sites that have it, built once per response
// loadCMSCategories hands out.
func cmsCategorySlugs(response map[string]interface{}) map[string]int {
	if last := lastCategorySlugIndex.Load(); last != nil && reflect.ValueOf(last.response).Pointer() == reflect.ValueOf(response).Pointer() {
		return last.slugs
	}
	slugs := make(map[string]int)
	data, _ := response["data"].(map[string]interface{})
	for domain := range data {
		// A slug counts once per site, as a category or a subcategory.
		own := make(map[string]bool)
		for _, c := range extractSitemapCategories(response, domain) {
			own[c.Slug] = true
			for _, sub := range c.Subcategories {
				own[sub.Slug] = true
			}
		}
		for slug := range own {
			slugs[slug]++
		}
	}
	lastCategorySlugIndex.Store(&cmsCategorySlugIndex{response: response, slugs: slugs})
	return slugs
}

// siteArticleIDsTTL is how long a site's set of listed article IDs is reused
// before it is built again from the (cached) category listings.
const siteArticleIDsTTL = 10 * time.Minute

type siteArticleIDs struct {
	ids   map[string]bool
	built time.Time
}

// siteArticleIDCache maps a domain to its *siteArticleIDs.
var siteArticleIDCache sync.Map

// siteListsArticle reports whether the site's category listings include the
// article, from a per-site ID set rather than parsing every listing per request.
func siteListsArticle(domain, articleID string) (bool, error) {
	if cached, ok := siteArticleIDCache.Load(domain); ok {
		if set := cached.(*siteArticleIDs); time.Since(set.built) < siteArticleIDsTTL {
			return set.ids[articleID], nil
		}
	}
	articles, err := fetchAllArticlesForDomain(domain)
	if err != nil {
		return false, err
	}
	ids := make(map[string]bool, len(articles))
	for _, item := range articles {
		if article, ok := item.(map[string]interface{}); ok {
			if id := firstNonEmptyField(article, "id", "article_id"); id != "" {
				ids[id] = true
			}
		}
	}
	siteArticleIDCache.Store(domain, &siteArticleIDs{ids: ids, built: time.Now()})
	return ids[articleID], nil
}
