package routes

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"sync/atomic"
	"testing"
	"time"

	"bitbucket.org/imediabrands/oos-service/internal/cache"
	"bitbucket.org/imediabrands/oos-service/internal/cms"
	"bitbucket.org/imediabrands/oos-service/middlewares"
	"github.com/julienschmidt/httprouter"
	"github.com/spf13/viper"
)

const testShopConfig = `{
	"displayName": "Shop Test",
	"template": "shop",
	"shared": {"shop": {"affiliate": "shoptest.com", "productSlug": "title",
		"pages": {"deals": {"title": "New Arrivals", "skus": ["94317661"]}, "topBrands": {}}}},
	"sitemapPages": ["/", "/about", "/deals"]
}`

// testShopProduct is product/94317661 as the shop API answered it on
// 2026-11-17 (shop/live/api/product_94317661_dealtimes.com.json), the Buy
// link shortened.
const testShopProduct = `{"success":true,"data":{"product_details":{"id":"1080986","price":"86.489998",
	"title_string":"FoodSaver White Food Vacuum Sealer",
	"description_string":"The FoodSaver Everyday VS0230 is compact, powerful and easy to use. Designed for ease of use with key vacuum and vacuum/seal modes. Works will all sizes of FoodSaver bags and rolls including 11\" items.",
	"image_small":"https://ak1.ostkcdn.com/images/x/FoodSaver-White-Food-Vacuum-Sealer.jpg",
	"image_zoom":"https://ak1.ostkcdn.com/images/x/FoodSaver-White-Food-Vacuum-Sealer.jpg",
	"product_name":"FoodSaver White Food Vacuum Sealer","merchant":"bedbathbeyond","availability":"in stock",
	"currency":"USD","category":"Specialty Appliances","brand":"FoodSaver","master_category":"Home & Kitchen",
	"sku":"94317661",
	"feature":"{\"color\":\"White\",\"gtin\":\"033413004419\",\"mpn\":\"2187313\",\"condition\":\"new\"}"},
	"redirect_url":"http://90701.click.validclick.net/cad.php?given_feed_id=3787"}}`

// testShopMasters is getMasterCategories' list, shortened.
const testShopMasters = `{"success":true,"data":[{"id":1,"master_category":"Fashion"},{"id":4,"master_category":"Home & Kitchen"},{"id":8,"master_category":"Beauty & Health"}]}`

// useTestShopAPI points the shop API at a test server answering like the
// commonshop API, with an empty shopCache; it returns the count of upstream
// requests.
func useTestShopAPI(t *testing.T) *int32 {
	t.Helper()
	var hits int32
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		atomic.AddInt32(&hits, 1)
		switch {
		case r.URL.Path == "/commonshop/getMasterCategories":
			io.WriteString(w, testShopMasters)
		case r.URL.Path == "/commonshop/search":
			// Like the API, a "-" in a category reads as a space; only "T-Shirts"
			// is a category with a "-" in its name.
			switch r.URL.Query().Get("category") {
			case "T-Shirts":
				io.WriteString(w, `{"success":true,"data":{"result":[{"sku":"1","category":"T-Shirts"}],"metaInfo":{"total":"1234","total_found":"1234"}}}`)
			case "Vacuum-Food-Sealers":
				io.WriteString(w, `{"success":true,"data":{"result":[{"sku":"2","category":"Vacuum Food Sealers"}],"metaInfo":{"total":"4553","total_found":"4553"}}}`)
			default:
				io.WriteString(w, `{"success":true,"data":{"result":[],"metaInfo":{"total":"0","total_found":"0"}}}`)
			}
		case r.URL.Path == "/commonshop/product/94317661":
			if r.URL.Query().Get("affiliate") == "unknown.com" {
				w.WriteHeader(http.StatusBadRequest)
				io.WriteString(w, `{"success":false,"message":"Invalid affiliate"}`)
				return
			}
			io.WriteString(w, testShopProduct)
		case r.URL.Path == "/commonshop/product/SLASH":
			io.WriteString(w, `{"success":true,"data":{"product_details":{"sku":"SLASH","product_name":"50/55 TV Stand"}}}`)
		case r.URL.Path == "/commonshop/product/BROKEN":
			w.WriteHeader(http.StatusInternalServerError)
		case r.URL.Path == "/commonshop/suggest":
			io.WriteString(w, `{"success":true,"data":["`+r.URL.Query().Get("keyword")+` sealer"]}`)
		default:
			w.WriteHeader(http.StatusNotFound)
			io.WriteString(w, `{"success":false,"message":"Product not found"}`)
		}
	}))
	t.Cleanup(srv.Close)
	viper.Set("shop_api_base_url", srv.URL)
	t.Cleanup(func() { viper.Set("shop_api_base_url", "") })
	orig := shopCache
	shopCache = cache.NewWithLimit(shopCacheTTL, shopCacheMaxEntries)
	t.Cleanup(func() { shopCache = orig })
	return &hits
}

// jsonAmp is "&" as marshalJSONLD writes it.
var jsonAmp = string(rune(92)) + "u0026"

// otherHandler stands for the route's handler on other sites.
var otherHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })

func TestIsShopSite(t *testing.T) {
	if !isShopSite(testClientConfig(t, testShopConfig)) || isShopSite(testClientConfig(t, `{"template": "directory"}`)) || isShopSite(nil) {
		t.Error("isShopSite")
	}
	if !usesSiteTemplate(map[string]interface{}{"template": "shop"}) {
		t.Error("the shop template has no not-found page title")
	}
}

func TestParseShopSearch(t *testing.T) {
	for _, tt := range []struct {
		raw     string
		want    shopSearchParams
		changed bool
	}{
		{"", shopSearchParams{}, false},
		{"master_category=Home+%26+Kitchen", shopSearchParams{MasterCategory: "Home & Kitchen"}, false},
		{"master_category=Home%20%26%20Kitchen&page=2", shopSearchParams{MasterCategory: "Home & Kitchen", Page: 2}, false},
		{"master_category=Home-sp--and--sp-Kitchen", shopSearchParams{MasterCategory: "Home & Kitchen"}, true},
		{"category=Men-obl-s-sp-Jackets-sp--and--sp-Coats", shopSearchParams{Category: "Men's Jackets & Coats"}, true},
		{"category=Gloves--and--Mittens", shopSearchParams{Category: "Gloves & Mittens"}, true},
		{"brand=New-sp-Balance&master_category=Sports", shopSearchParams{MasterCategory: "Sports", Brand: "New Balance"}, true},
		// beyondcheap's unencoded "&", as a browser sends it
		{"master_category=Home%20&%20Kitchen", shopSearchParams{MasterCategory: "Home & Kitchen"}, true},
		{"master_category=Home+&+Kitchen&category=Rugs", shopSearchParams{MasterCategory: "Home & Kitchen", Category: "Rugs"}, true},
		{"category=Bed+&+Bath+&+Beyond", shopSearchParams{Category: "Bed & Bath & Beyond"}, true},
		// the legacy app's pagination URL
		{"keyword=&master_category=Home+%26+Kitchen&category=&brand=&prices=0&availability=0&page=2&per_page=20&sort=", shopSearchParams{MasterCategory: "Home & Kitchen", Page: 2}, true},
		{"keyword=vacuum&sort=price&prices=3&availability=in+stock", shopSearchParams{Keyword: "vacuum", Prices: "3", Availability: "in stock", Sort: "price"}, false},
		{"keyword=vacuum&sort=relevance", shopSearchParams{Keyword: "vacuum"}, true},
		{"keyword=vacuum&sort=price-desc&page=1", shopSearchParams{Keyword: "vacuum", Sort: "price-desc"}, true},
		{"keyword=+a++b+", shopSearchParams{Keyword: "a b"}, true},
		{"keyword=a&keyword=b", shopSearchParams{Keyword: "a"}, true},
		{"keyword=a&utm_source=x", shopSearchParams{Keyword: "a"}, true},
		{"prices=9&page=x&page=3", shopSearchParams{}, true},
		{"keyword=%zz", shopSearchParams{}, true},
	} {
		got, changed := parseShopSearch(tt.raw)
		if got != tt.want || changed != tt.changed {
			t.Errorf("parseShopSearch(%q) = %+v, %v; want %+v, %v", tt.raw, got, changed, tt.want, tt.changed)
		}
	}
}

func TestShopSearchParamsQuery(t *testing.T) {
	p := shopSearchParams{Keyword: "a&b c", MasterCategory: "Home & Kitchen", Category: "Men's Jackets", Brand: "B", Prices: "2", Availability: "in stock", Sort: "price", Page: 3}
	want := "keyword=a%26b+c&master_category=Home+%26+Kitchen&category=Men%27s+Jackets&brand=B&prices=2&availability=in+stock&sort=price&page=3"
	if got := p.query(true); got != want {
		t.Errorf("query = %q, want %q", got, want)
	}
	if got := p.path(false); strings.Contains(got, "sort=") || !strings.HasPrefix(got, "/search?") {
		t.Errorf("path(false) = %q", got)
	}
	if got := (shopSearchParams{}).path(true); got != "/search" {
		t.Errorf("empty path = %q", got)
	}
	// The canonical query reads back as itself.
	if back, changed := parseShopSearch(want); changed || back != p {
		t.Errorf("round trip = %+v, %v", back, changed)
	}
}

type fakeShopLookups struct {
	masters    []string
	categories map[string]string // searched category → the API's spelling
	err        error
}

func (f fakeShopLookups) MasterCategories(context.Context) ([]string, error) { return f.masters, f.err }
func (f fakeShopLookups) CategoryName(_ context.Context, c string) (string, bool, error) {
	name, found := f.categories[c]
	return name, found, f.err
}

func TestResolveShopSearch(t *testing.T) {
	api := fakeShopLookups{masters: []string{"Fashion", "Home & Kitchen", "Baby & Toys Products"}, categories: map[string]string{
		"T-Shirts": "T-Shirts", "Vacuum-Food-Sealers": "Vacuum Food Sealers", "Odd-Name": ""}}
	for _, tt := range []struct {
		in, want shopSearchParams
		lookups  shopLookups
		changed  bool
	}{
		{shopSearchParams{MasterCategory: "Home & Kitchen"}, shopSearchParams{MasterCategory: "Home & Kitchen"}, api, false},
		{shopSearchParams{MasterCategory: "home-and-kitchen"}, shopSearchParams{MasterCategory: "Home & Kitchen"}, api, true},
		{shopSearchParams{MasterCategory: "fashion"}, shopSearchParams{MasterCategory: "Fashion"}, api, true},
		{shopSearchParams{MasterCategory: "Baby-&-Toys-Products"}, shopSearchParams{MasterCategory: "Baby & Toys Products"}, api, true},
		{shopSearchParams{MasterCategory: "Home"}, shopSearchParams{MasterCategory: "Home"}, api, false},
		{shopSearchParams{MasterCategory: "Not-A-Master"}, shopSearchParams{MasterCategory: "Not A Master"}, api, true},
		{shopSearchParams{Category: "Vacuum-Food-Sealers"}, shopSearchParams{Category: "Vacuum Food Sealers"}, api, true},
		{shopSearchParams{Category: "T-Shirts"}, shopSearchParams{Category: "T-Shirts"}, api, false},
		{shopSearchParams{Category: "No-Such-Thing"}, shopSearchParams{Category: "No Such Thing"}, api, true},
		// Found, but no product's category is spelled like it: left as it is.
		{shopSearchParams{Category: "Odd-Name"}, shopSearchParams{Category: "Odd-Name"}, api, false},
		{shopSearchParams{Category: "Rugs"}, shopSearchParams{Category: "Rugs"}, api, false},
		// The API can't tell: values stay.
		{shopSearchParams{MasterCategory: "home-and-kitchen", Category: "Vacuum-Food-Sealers"}, shopSearchParams{MasterCategory: "home-and-kitchen", Category: "Vacuum-Food-Sealers"}, fakeShopLookups{err: errors.New("down")}, false},
	} {
		p := tt.in
		changed := resolveShopSearch(context.Background(), &p, tt.lookups)
		if p != tt.want || changed != tt.changed {
			t.Errorf("resolveShopSearch(%+v) = %+v, %v; want %+v, %v", tt.in, p, changed, tt.want, tt.changed)
		}
	}
}

func TestShopSearchHandler(t *testing.T) {
	useTestShopAPI(t)
	tpl := pageTemplatesFrom("../web/templates")
	handler := directorySearchHandler(otherHandler, tpl)
	shop := testClientConfig(t, `{"displayName": "Shop Test", "template": "shop",
		"seoMeta": {"shopSearch": {"title": "{query} deals at {displayName}"}}}`)

	for _, tt := range []struct {
		name, target string
		status       int
		location     string
	}{
		{"legacy encoding", "/search?master_category=Home-sp--and--sp-Kitchen", 301, "/search?master_category=Home+%26+Kitchen"},
		{"unencoded &", "/search?master_category=Home%20&%20Kitchen&category=", 301, "/search?master_category=Home+%26+Kitchen"},
		{"slug master", "/search?master_category=home-and-kitchen&page=1", 301, "/search?master_category=Home+%26+Kitchen"},
		{"menu slug category", "/search?category=Vacuum-Food-Sealers", 301, "/search?category=Vacuum+Food+Sealers"},
		{"legacy pagination", "/search?keyword=&master_category=Fashion&category=&brand=&page=2&per_page=20&sort=", 301, "/search?master_category=Fashion&page=2"},
		{"trailing slash", "/search/?keyword=Adidas", 301, "/search?keyword=Adidas"},
		{"category with a dash", "/search?category=T-Shirts", 200, ""},
		{"canonical", "/search?master_category=Home+%26+Kitchen&page=2", 200, ""},
		{"search", "/search?keyword=vacuum&sort=price", 200, ""},
	} {
		t.Run(tt.name, func(t *testing.T) {
			rec := serveWith(handler, shop, tt.target, nil)
			if rec.Code != tt.status {
				t.Fatalf("status = %d, want %d", rec.Code, tt.status)
			}
			if got := rec.Header().Get("Location"); got != tt.location {
				t.Errorf("Location = %q, want %q", got, tt.location)
			}
		})
	}

	t.Run("category page head", func(t *testing.T) {
		rec := serveWith(handler, shop, "/search?master_category=Home+%26+Kitchen&category=Rugs&page=2", nil)
		html := rec.Body.String()
		for _, want := range []string{
			"<title>Rugs - Shop Test - Page 2</title>",
			`<link rel="canonical" href="https://localtest.com/search?master_category=Home&#43;%26&#43;Kitchen&amp;category=Rugs&amp;page=2" />`,
			`"name": "Home ` + jsonAmp + ` Kitchen"`,
			`"item": "https://localtest.com/search?master_category=Home+%26+Kitchen` + jsonAmp + `category=Rugs"`,
		} {
			if !strings.Contains(html, want) {
				t.Errorf("missing %s", want)
			}
		}
		if got := rec.Header().Get("X-Robots-Tag"); got != "index, follow" {
			t.Errorf("X-Robots-Tag = %q", got)
		}
	})
	t.Run("search page head", func(t *testing.T) {
		rec := serveWith(handler, shop, "/search?keyword=vacuum&sort=price", nil)
		html := rec.Body.String()
		for _, want := range []string{
			"<title>vacuum deals at Shop Test</title>",
			`<link rel="canonical" href="https://localtest.com/search?keyword=vacuum" />`,
		} {
			if !strings.Contains(html, want) {
				t.Errorf("missing %s", want)
			}
		}
		if got := rec.Header().Get("X-Robots-Tag"); got != "noindex, follow" {
			t.Errorf("X-Robots-Tag = %q", got)
		}
		if strings.Contains(html, "oos-breadcrumb-schema") {
			t.Error("search page has a BreadcrumbList")
		}
	})

	// Other sites: unchanged.
	for _, raw := range []string{`{"template": "editorial"}`, `{}`} {
		config := testClientConfig(t, raw)
		if rec := serveWith(handler, config, "/search?master_category=Home-sp--and--sp-Kitchen", nil); rec.Code != http.StatusTeapot {
			t.Errorf("%s: /search status = %d, want the article search", raw, rec.Code)
		}
		rec := serveWith(handler, config, "/search/?keyword=a", nil)
		if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/search?keyword=a" {
			t.Errorf("%s: /search/ = %d %q, want 301 /search?keyword=a", raw, rec.Code, rec.Header().Get("Location"))
		}
	}
	if rec := serveWith(handler, testClientConfig(t, testDirectoryConfig), "/search?keyword=dentists", nil); rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/search?s=dentists" {
		t.Errorf("directory site: %d %q", rec.Code, rec.Header().Get("Location"))
	}
}

func TestShopTitleSlug(t *testing.T) {
	long := strings.Repeat("a", 119) + "\U0001F600b"
	for title, want := range map[string]string{
		"FoodSaver White Food Vacuum Sealer":    "FoodSaver-White-Food-Vacuum-Sealer",
		"Live And Let Die  -  DVD - Best Buy":   "Live-And-Let-Die---DVD---Best-Buy",
		"Men's Tee (Blue) 100% Cotton, S/M & L": "Men's-Tee-(Blue)-100%25-Cotton%2C-S%2FM-%26-L",
		"Café ° tab\there":                      "Caf%C3%A9-%C2%B0-tab-here",
		strings.Repeat("x", 130):                strings.Repeat("x", 120),
		// The cut would split the emoji's surrogate pair: it is left out.
		long:                                     strings.Repeat("a", 119),
		strings.Repeat("a", 118) + "\U0001F600b": strings.Repeat("a", 118) + "%F0%9F%98%80",
	} {
		if got := shopTitleSlug(title); got != want {
			t.Errorf("shopTitleSlug(%q) = %q, want %q", title, got, want)
		}
	}
}

func TestShopProductHandler(t *testing.T) {
	hits := useTestShopAPI(t)
	tpl := pageTemplatesFrom("../web/templates")
	handler := shopProductHandler(otherHandler, tpl)
	shop := testClientConfig(t, testShopConfig)
	product := func(config *middlewares.ClientConfig, sku, slug string) *httptest.ResponseRecorder {
		params := httprouter.Params{{Key: "sku", Value: sku}}
		target := "/product_detail/" + sku
		if slug != "" {
			params = append(params, httprouter.Param{Key: "slug", Value: slug})
			target += "/" + slug
		}
		return serveWith(handler, config, target, params)
	}

	rec := product(shop, "94317661", "anything")
	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d", rec.Code)
	}
	html := rec.Body.String()
	for _, want := range []string{
		"<title>FoodSaver White Food Vacuum Sealer - Shop Test</title>",
		`<link rel="canonical" href="https://localtest.com/product_detail/94317661/FoodSaver-White-Food-Vacuum-Sealer" />`,
		`<meta property="og:image" content="https://ak1.ostkcdn.com/images/x/FoodSaver-White-Food-Vacuum-Sealer.jpg" />`,
		`<meta name="description" content="The FoodSaver Everyday VS0230 is compact, powerful and easy to use. Designed for ease of use with key vacuum and vacuum/seal modes. Works will all sizes of"`,
		`"@type": "Product"`,
		`"gtin12": "033413004419"`,
		`"mpn": "2187313"`,
		`"price": "86.49"`,
		`"priceCurrency": "USD"`,
		`"availability": "https://schema.org/InStock"`,
		`"brand": {`,
		`"item": "https://localtest.com/search?master_category=Home+%26+Kitchen"`,
	} {
		if !strings.Contains(html, want) {
			t.Errorf("missing %s", want)
		}
	}
	if got := rec.Header().Get("X-Robots-Tag"); got != "index, follow" {
		t.Errorf("X-Robots-Tag = %q", got)
	}
	before := atomic.LoadInt32(hits)
	product(shop, "94317661", "other-slug")
	if atomic.LoadInt32(hits) != before {
		t.Error("the product was fetched again within the cache TTL")
	}

	index := testClientConfig(t, `{"displayName": "Shop Test", "template": "shop", "shared": {"shop": {"productSlug": "index"}},
		"seoMeta": {"shopProduct": {"title": "{name} | {brand} | {displayName}", "description": "Buy {name} in {category}."}}}`)
	html = product(index, "94317661", "1").Body.String()
	for _, want := range []string{
		`<link rel="canonical" href="https://localtest.com/product_detail/94317661/1" />`,
		"<title>FoodSaver White Food Vacuum Sealer | FoodSaver | Shop Test</title>",
		`content="Buy FoodSaver White Food Vacuum Sealer in Specialty Appliances."`,
	} {
		if !strings.Contains(html, want) {
			t.Errorf("productSlug index: missing %s", want)
		}
	}

	t.Run("API 404", func(t *testing.T) {
		rec := product(shop, "1544291", "x")
		if rec.Code != http.StatusNotFound || rec.Header().Get("X-Robots-Tag") != "noindex, nofollow" {
			t.Errorf("status = %d, robots %q", rec.Code, rec.Header().Get("X-Robots-Tag"))
		}
	})
	for name, config := range map[string]*middlewares.ClientConfig{
		"API 400": testClientConfig(t, `{"displayName": "Shop Test", "template": "shop", "shared": {"shop": {"affiliate": "unknown.com"}}}`),
		"API 500": shop,
	} {
		t.Run(name, func(t *testing.T) {
			sku := "94317661"
			if name == "API 500" {
				sku = "BROKEN"
			}
			rec := product(config, sku, "x")
			html := rec.Body.String()
			if rec.Code != http.StatusOK || rec.Header().Get("X-Robots-Tag") != "noindex, follow" || rec.Header().Get("Cache-Control") != "no-store" {
				t.Errorf("status = %d, robots %q, cache %q", rec.Code, rec.Header().Get("X-Robots-Tag"), rec.Header().Get("Cache-Control"))
			}
			if !strings.Contains(html, "<title>Product Details - Shop Test</title>") || strings.Contains(html, `rel="canonical"`) || strings.Contains(html, `"Product"`) {
				t.Error("error shell: wrong title, or a canonical / Product schema")
			}
		})
	}
	t.Run("no slug", func(t *testing.T) {
		if rec := product(shop, "94317661", ""); rec.Code != http.StatusNotFound {
			t.Errorf("status = %d, want 404", rec.Code)
		}
	})
	t.Run("other sites", func(t *testing.T) {
		if rec := product(testClientConfig(t, `{"template": "editorial"}`), "94317661", "x"); rec.Code != http.StatusTeapot {
			t.Errorf("status = %d, want the not-found handler's", rec.Code)
		}
	})
}

func TestShopPageHandler(t *testing.T) {
	tpl := pageTemplatesFrom("../web/templates")
	shop := testClientConfig(t, testShopConfig)
	deals := shopPageHandler(shopDealsPage, otherHandler, tpl)

	rec := serveWith(deals, shop, "/deals", nil)
	html := rec.Body.String()
	if rec.Code != http.StatusOK || !strings.Contains(html, "<title>New Arrivals - Shop Test</title>") ||
		!strings.Contains(html, `<link rel="canonical" href="https://localtest.com/deals" />`) || rec.Header().Get("X-Robots-Tag") != "index, follow" {
		t.Errorf("/deals: %d, robots %q", rec.Code, rec.Header().Get("X-Robots-Tag"))
	}
	if rec := serveWith(deals, shop, "/deals/?a=1", nil); rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/deals?a=1" {
		t.Errorf("/deals/: %d %q", rec.Code, rec.Header().Get("Location"))
	}
	if html := serveWith(shopPageHandler(shopTopBrandsPage, otherHandler, tpl), shop, "/top-brands", nil).Body.String(); !strings.Contains(html, "<title>Top Brands - Shop Test</title>") {
		t.Error("/top-brands without a title: no default title")
	}
	// Not the site's page, or not a shop site: routed as before.
	if rec := serveWith(shopPageHandler(shopCategoriesPage, otherHandler, tpl), shop, "/categories", nil); rec.Code != http.StatusTeapot {
		t.Errorf("shop site without /categories: %d", rec.Code)
	}
	if rec := serveWith(deals, testClientConfig(t, `{"template": "editorial", "shared": {"shop": {"pages": {"deals": {}}}}}`), "/deals", nil); rec.Code != http.StatusTeapot {
		t.Errorf("editorial site: %d", rec.Code)
	}

	// /categories: directory sites keep theirs, shop sites with the page get it.
	categories := directoryCategoriesHandler(shopPageHandler(shopCategoriesPage, otherHandler, tpl), tpl)
	withCategories := testClientConfig(t, `{"displayName": "Shop Test", "template": "shop", "shared": {"shop": {"pages": {"categories": {"title": "All Categories"}}}}}`)
	if html := serveWith(categories, withCategories, "/categories", nil).Body.String(); !strings.Contains(html, "<title>All Categories - Shop Test</title>") {
		t.Error("shop /categories")
	}
	if html := serveWith(categories, testClientConfig(t, testDirectoryConfig), "/categories", nil).Body.String(); !strings.Contains(html, "<title>Categories - Local Test</title>") {
		t.Error("directory /categories")
	}
	if rec := serveWith(categories, testClientConfig(t, `{"template": "magazine"}`), "/categories", nil); rec.Code != http.StatusTeapot {
		t.Errorf("magazine /categories: %d", rec.Code)
	}
}

func TestDataShopSuggestHandler(t *testing.T) {
	useTestShopAPI(t)
	rec := serveWith(DataShopSuggestHandler(), nil, "/data/shop/suggest?keyword=vacuum", nil)
	if rec.Body.String() != `{"success":true,"data":[]}` || !strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json") {
		t.Errorf("stub = %q", rec.Body.String())
	}
	viper.Set("shop_suggest_path", "commonshop/suggest")
	t.Cleanup(func() { viper.Set("shop_suggest_path", "") })
	if got := serveWith(DataShopSuggestHandler(), nil, "/data/shop/suggest?keyword=food+saver", nil).Body.String(); got != `{"success":true,"data":["food saver sealer"]}` {
		t.Errorf("proxied = %q", got)
	}
}

func TestShopSitemapPages(t *testing.T) {
	useTestShopAPI(t)
	shop := testClientConfig(t, testShopConfig)
	if got := strings.Join(sitemapPagesFromConfig(shop), " "); got != "/ /about /deals /top-brands" {
		t.Errorf("sitemapPages: %q", got)
	}
	if got := strings.Join(sitemapPagesFromConfig(testClientConfig(t, `{"template": "shop", "shared": {"shop": {"pages": {"topBrands": {}}}}}`)), " "); got != "/ /about /contact /privacy /terms /top-brands" {
		t.Errorf("default sitemapPages: %q", got)
	}
	if got := strings.Join(sitemapPagesFromConfig(testClientConfig(t, `{"template": "magazine", "sitemapPages": ["/", "/deals"]}`)), " "); got != "/ /sitemap" {
		t.Errorf("magazine site: %q", got)
	}

	body := serveWith(SitemapPagesHandler(), shop, "/sitemap_pages.xml", nil).Body.String()
	for _, want := range []string{"<loc>https://localtest.com/deals</loc>", "<loc>https://localtest.com/search?master_category=Home+%26+Kitchen</loc>"} {
		if !strings.Contains(strings.ReplaceAll(body, "&amp;", "&"), want) {
			t.Errorf("sitemap_pages.xml: missing %s", want)
		}
	}
	if body := serveWith(SitemapPagesHandler(), testClientConfig(t, `{"template": "magazine"}`), "/sitemap_pages.xml", nil).Body.String(); strings.Contains(body, "master_category") {
		t.Error("a magazine site lists shop listings")
	}
}

func TestShopNotFoundPage(t *testing.T) {
	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "https://localtest.com/nope", nil)
	req = req.WithContext(context.WithValue(req.Context(), middlewares.ClientConfigKey, testClientConfig(t, testShopConfig)))
	serveNotFoundPage(rec, req, pageTemplatesFrom("../web/templates"))
	if rec.Code != http.StatusNotFound || !strings.Contains(rec.Body.String(), "<title>Page not found - Shop Test</title>") {
		t.Errorf("status %d, body without the site template's 404 title", rec.Code)
	}
}

func TestCategoryPaths(t *testing.T) {
	config := testClientConfig(t, `{"template": "shop", "shared": {"categoryPaths": {"Blogs": "blog", "Bad": "Not A Slug", "Shop Stuff": "shop"}}}`)
	paths := categoryPathsFromConfig(config)
	if paths == nil || len(*paths) != 1 || (*paths)["blogs"] != "blog" {
		t.Fatalf("categoryPathsFromConfig = %v", paths)
	}
	if categoryPathsFromConfig(testClientConfig(t, `{}`)) != nil {
		t.Error("a site without categoryPaths has some")
	}
	for name, want := range map[string]string{"Blogs": "blog", "BLOGS": "blog", "Health Tips": "health-tips"} {
		if got := paths.slug(name); got != want {
			t.Errorf("slug(%q) = %q, want %q", name, got, want)
		}
	}
	var none *categoryPaths
	if got := none.slug("Blogs"); got != "blogs" {
		t.Errorf("nil slug = %q", got)
	}

	opts := articleURLOptionsFromConfig(config)
	meta := articlePageMeta{Category: "Blogs", SlugTitle: "Smart Home Workout Equipment"}
	if got := canonicalArticlePath(forArticleURL(meta, opts), "1780441"); got != "/blog/1780441-smart-home-workout-equipment" {
		t.Errorf("canonical article path = %q", got)
	}
	if got := articleCanonicalRedirectPath(forArticleURL(meta, opts), "1780441", "/blogs/1780441-smart-home-workout-equipment"); got != "/blog/1780441-smart-home-workout-equipment" {
		t.Errorf("redirect from the name's slug = %q", got)
	}
	if got := buildSitemapArticlePath(map[string]interface{}{"id": "1780441", "title": "Smart Home Workout Equipment"}, "Blogs", opts); got != "/blog/1780441-smart-home-workout-equipment" {
		t.Errorf("sitemap article path = %q", got)
	}

	// Route checks and sitemaps with the CMS listing the site's "Blogs".
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Query().Get("catId") != "" || strings.Contains(r.URL.RawQuery, "1092") {
			io.WriteString(w, `{"data":[{"id":"1780441","title":"Smart Home Workout Equipment","category":"Blogs"}]}`)
			return
		}
		io.WriteString(w, `{"data":{"localtest.com":[{"cat_id":"1092","cat_name":"Blogs"}]}}`)
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()

	req := httptest.NewRequest(http.MethodGet, "https://localtest.com/blog", nil)
	req = req.WithContext(context.WithValue(req.Context(), middlewares.ClientConfigKey, config))
	if categoryRouteMissing(req, "blog", "") || !categoryRouteMissing(req, "blogs", "") {
		t.Error("categoryRouteMissing: /blog should be the category, /blogs no page")
	}
	// A domain the CMS doesn't list: no category pages on a shop site, unchecked elsewhere.
	unlisted := httptest.NewRequest(http.MethodGet, "https://unlisted.com/deals", nil)
	if !categoryRouteMissing(unlisted.WithContext(context.WithValue(unlisted.Context(), middlewares.ClientConfigKey, config)), "deals", "") {
		t.Error("categoryRouteMissing: an unlisted shop domain should have no category pages")
	}
	if categoryRouteMissing(unlisted.WithContext(context.WithValue(unlisted.Context(), middlewares.ClientConfigKey, testClientConfig(t, `{}`))), "deals", "") {
		t.Error("categoryRouteMissing: an unlisted non-shop domain should stay unchecked")
	}
	if body := serveWith(SitemapIndexHandler(), config, "/sitemap.xml", nil).Body.String(); !strings.Contains(body, "https://localtest.com/sitemap_blog.xml") {
		t.Errorf("sitemap index without sitemap_blog.xml: %s", body)
	}
	body := serveWith(SitemapCategoryHandler("blog"), config, "/sitemap_blog.xml", nil).Body.String()
	for _, want := range []string{"<loc>https://localtest.com/blog</loc>", "<loc>https://localtest.com/blog/1780441-smart-home-workout-equipment</loc>"} {
		if !strings.Contains(body, want) {
			t.Errorf("sitemap_blog.xml: missing %s in %s", want, body)
		}
	}
}

func TestCMSUnlistedShopSite(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Query().Get("action") {
		case "getcategoryarticles":
			io.WriteString(w, `{"data":[{"id":"1775853","title":"Small Space Living Ideas","category":"Blogs"}]}`)
		case "getarticledata":
			io.WriteString(w, `{"data":{"id":"1775853","title":"Small Space Living Ideas","category":"Blogs"}}`)
		default:
			io.WriteString(w, `{"data":{"listed.com":[{"cat_id":"1088","cat_name":"Blogs"}]}}`)
		}
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()

	shop := testClientConfig(t, `{"displayName": "Shop Test", "template": "shop"}`)
	editorial := testClientConfig(t, `{"displayName": "Other", "template": "editorial"}`)
	serve := func(handler http.Handler, config *middlewares.ClientConfig, host, target string, params httprouter.Params) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodGet, "https://"+host+target, nil)
		ctx := context.WithValue(req.Context(), middlewares.ClientConfigKey, config)
		if params != nil {
			ctx = context.WithValue(ctx, httprouter.ParamsKey, params)
		}
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, req.WithContext(ctx))
		return rec
	}
	tpl := pageTemplatesFrom("../web/templates")

	for _, tt := range []struct {
		name        string
		handler     http.Handler
		target      string
		params      httprouter.Params
		shopWant    string // in the unlisted shop site's body
		foreignText string // another site's content, which only other sites may show
	}{
		{"categories", DataCategoriesHandler(), "/data/categories", nil, `{"data":{"unlisted.com":[]}}`, "1088"},
		{"category articles", DataCategoryArticlesHandler(), "/data/category-articles/1088", httprouter.Params{{Key: "catId", Value: "1088"}}, `"data":[]`, "Small Space"},
		{"articles", DataArticlesHandler(), "/data/articles", nil, `"data":[]`, "Small Space"},
		{"article", DataArticleHandler(), "/data/article/1775853", httprouter.Params{{Key: "id", Value: "1775853"}}, `{"data":false}`, "Small Space"},
		{"sitemap index", SitemapIndexHandler(), "/sitemap.xml", nil, "sitemap_pages.xml", "sitemap_blogs.xml"},
	} {
		t.Run(tt.name, func(t *testing.T) {
			body := serve(tt.handler, shop, "unlisted.com", tt.target, tt.params).Body.String()
			if !strings.Contains(body, tt.shopWant) || strings.Contains(body, tt.foreignText) {
				t.Errorf("shop site: %s", body)
			}
			if body := serve(tt.handler, editorial, "unlisted.com", tt.target, tt.params).Body.String(); !strings.Contains(body, tt.foreignText) {
				t.Errorf("editorial site lost its fallback: %s", body)
			}
		})
	}

	// Article URLs: a 404, never a 301 to the other site's article.
	for _, target := range []string{"/blog/1775853-x", "/article/1775853", "/category/1088"} {
		params, _ := articleRouteParams(target)
		rec := serve(articleDetailHandler(tpl), shop, "unlisted.com", target, params)
		if rec.Code != http.StatusNotFound {
			t.Errorf("%s: status %d, Location %q; want 404", target, rec.Code, rec.Header().Get("Location"))
		}
	}
	if rec := serve(articleByCategoryHandler(tpl), shop, "unlisted.com", "/articles/category/1088", httprouter.Params{{Key: "category", Value: "1088"}}); rec.Code != http.StatusNotFound {
		t.Errorf("/articles/category/1088: status %d", rec.Code)
	}
	// A listed shop site keeps its own.
	if body := serve(DataCategoriesHandler(), shop, "listed.com", "/data/categories", nil).Body.String(); !strings.Contains(body, "Blogs") {
		t.Errorf("listed shop site: %s", body)
	}
}

func TestShopFixRound1(t *testing.T) {
	useTestShopAPI(t)
	tpl := pageTemplatesFrom("../web/templates")

	// price → prices
	if p, changed := parseShopSearch("keyword=foodsaver&price=2"); !changed || p != (shopSearchParams{Keyword: "foodsaver", Prices: "2"}) {
		t.Errorf("price=2: %+v, %v", p, changed)
	}

	// beyondcheap: a non-digit slug 301s to /1; digits and other sites' slugs don't.
	product := func(config *middlewares.ClientConfig, sku, slug string) *httptest.ResponseRecorder {
		return serveWith(shopProductHandler(otherHandler, tpl), config, "/product_detail/"+sku+"/"+slug,
			httprouter.Params{{Key: "sku", Value: sku}, {Key: "slug", Value: slug}})
	}
	index := testClientConfig(t, `{"displayName": "BC", "template": "shop", "shared": {"shop": {"productSlug": "index"}}}`)
	if rec := product(index, "94317661", "foo"); rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/product_detail/94317661/1" {
		t.Errorf("index slug foo: %d %q", rec.Code, rec.Header().Get("Location"))
	}
	if rec := product(index, "94317661", "2"); rec.Code != http.StatusOK {
		t.Errorf("index slug 2: %d", rec.Code)
	}
	if rec := product(index, "1544291", "foo"); rec.Code != http.StatusNotFound {
		t.Errorf("index dead sku: %d", rec.Code)
	}
	shop := testClientConfig(t, testShopConfig)
	if rec := product(shop, "94317661", "foo"); rec.Code != http.StatusOK {
		t.Errorf("title slug foo: %d", rec.Code)
	}
	// Product BreadcrumbList level 3 is the master + category listing.
	if html := product(shop, "94317661", "foo").Body.String(); !strings.Contains(html, `"item": "https://localtest.com/search?master_category=Home+%26+Kitchen`+jsonAmp+`category=Specialty+Appliances"`) {
		t.Error("product breadcrumb level 3 isn't the master + category listing")
	}

	// /index.php?/{path}
	for _, tt := range []struct{ path, query, target, rest string }{
		{"/index.php", "/deals", "/deals", ""},
		{"/index.php", "/about&utm_source=x", "/about", "utm_source=x"},
		{"/index.php/", "/blog/1780441-x", "/blog/1780441-x", ""},
	} {
		target, rest, ok := shopIndexPHPTarget(tt.path, tt.query)
		if !ok || target != tt.target || rest != tt.rest {
			t.Errorf("shopIndexPHPTarget(%q, %q) = %q, %q, %v", tt.path, tt.query, target, rest, ok)
		}
	}
	for _, query := range []string{"//evil.com", "/%2Fevil.com", "a=1", "", "/x\\y"} {
		if _, _, ok := shopIndexPHPTarget("/index.php", query); ok {
			t.Errorf("shopIndexPHPTarget(%q) matched", query)
		}
	}
	legacy := legacyURLMiddleware(otherHandler, tpl)
	withRule := testClientConfig(t, `{"template": "shop", "legacyUrls": {"redirects": [{"from": "^/index\\.php/?$", "to": "/"}]}}`)
	if rec := serveWith(legacy, withRule, "/index.php?/deals", nil); rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/deals" {
		t.Errorf("/index.php?/deals: %d %q", rec.Code, rec.Header().Get("Location"))
	}
	if rec := serveWith(legacy, testClientConfig(t, `{"template": "editorial"}`), "/index.php?/deals", nil); rec.Code != http.StatusTeapot {
		t.Errorf("editorial /index.php?/deals: %d", rec.Code)
	}

	// /sitemap: a shop site without pages.sitemap has none.
	noSitemap := testClientConfig(t, `{"template": "shop", "sitemapPages": ["/", "/about", "/sitemap"]}`)
	if shopHasSitemapPage(noSitemap) || !shopHasSitemapPage(testClientConfig(t, `{"template": "shop", "pages": {"sitemap": {"content": {"title": "Sitemap"}}}}`)) || !shopHasSitemapPage(testClientConfig(t, `{"template": "editorial"}`)) {
		t.Error("shopHasSitemapPage")
	}
	if got := strings.Join(sitemapPagesFromConfig(noSitemap), " "); got != "/ /about" {
		t.Errorf("sitemapPages without the page: %q", got)
	}
	if got := strings.Join(sitemapPagesFromConfig(testClientConfig(t, `{"template": "shop"}`)), " "); got != "/ /about /contact /privacy /terms" {
		t.Errorf("default sitemapPages without the page: %q", got)
	}
}

func TestDataShopDealsHandler(t *testing.T) {
	hits := useTestShopAPI(t)
	orig := shopDeals
	shopDeals = &shopDealsStore{deals: map[string]shopDeal{}, refreshing: map[string]bool{}}
	t.Cleanup(func() { shopDeals = orig })
	config := testClientConfig(t, `{"template": "shop", "shared": {"shop": {"affiliate": "shoptest.com",
		"pages": {"deals": {"skus": ["94317661", "1544291", "BROKEN", "94317661"]}}}}}`)
	skus, affiliate, _ := shopDealsSettings(config)
	if strings.Join(skus, " ") != "94317661 1544291 BROKEN" {
		t.Errorf("skus = %v", skus)
	}

	decode := func(rec *httptest.ResponseRecorder) shopDealsResponse {
		t.Helper()
		var r shopDealsResponse
		if err := json.Unmarshal(rec.Body.Bytes(), &r); err != nil {
			t.Fatal(err)
		}
		return r
	}
	// Cold: nothing known yet, so partial and empty, never waiting.
	if r := decode(serveWith(DataShopDealsHandler(), config, "/data/shop/deals", nil)); !r.Success || !r.Partial || len(r.Data) != 0 {
		t.Errorf("cold = %+v", r)
	}
	// Let the refresh the cold request started finish.
	for i := 0; i < 500; i++ {
		shopDeals.mu.Lock()
		running := shopDeals.refreshing[affiliate]
		shopDeals.mu.Unlock()
		if !running {
			break
		}
		time.Sleep(10 * time.Millisecond)
	}
	shopDeals.refresh(context.Background(), affiliate, skus)
	rec := serveWith(DataShopDealsHandler(), config, "/data/shop/deals", nil)
	r := decode(rec)
	// 94317661 live, 1544291 gone (404, left out), BROKEN failed (500): partial.
	if len(r.Data) != 1 || !strings.Contains(string(r.Data[0]), `"sku":"94317661"`) || !r.Partial || rec.Header().Get("Cache-Control") != "no-store" {
		t.Errorf("after refresh = %+v (%s)", r, rec.Header().Get("Cache-Control"))
	}
	shopDeals.mu.Lock()
	gone, failed := shopDeals.deals[shopDealKey(affiliate, "1544291")], shopDeals.deals[shopDealKey(affiliate, "BROKEN")]
	shopDeals.mu.Unlock()
	if !gone.Gone || failed.Gone || !failed.Failed {
		t.Errorf("gone = %+v, failed = %+v", gone, failed)
	}
	// Known SKUs aren't looked up again within the TTL; the failed one waits its retry.
	before := atomic.LoadInt32(hits)
	shopDeals.refresh(context.Background(), affiliate, skus)
	if atomic.LoadInt32(hits) != before {
		t.Error("a refresh within the TTL looked SKUs up again")
	}
	if !failed.due(failed.At.Add(shopDealsRetryAfter)) || gone.due(gone.At.Add(time.Hour)) || !gone.due(gone.At.Add(shopDealsTTL)) {
		t.Error("due times")
	}

	// All known and none failed: complete and cacheable.
	complete := testClientConfig(t, `{"template": "shop", "shared": {"shop": {"affiliate": "shoptest.com", "pages": {"deals": {"skus": ["94317661", "1544291"]}}}}}`)
	rec = serveWith(DataShopDealsHandler(), complete, "/data/shop/deals", nil)
	if r := decode(rec); r.Partial || len(r.Data) != 1 || rec.Header().Get("Cache-Control") != "public, max-age=300" {
		t.Errorf("complete = %+v", r)
	}
	// The background warmer follows cms_warm; without it the request above
	// started the lookups itself.
	if StartShopDealsWarmer() {
		t.Error("the deals warmer started without cms_warm")
	}
	viper.Set("cms_warm", true)
	t.Cleanup(func() { viper.Set("cms_warm", false) })
	if !StartShopDealsWarmer() {
		t.Error("the deals warmer didn't start with cms_warm")
	}

	// No deals page: 404.
	if rec := serveWith(DataShopDealsHandler(), testClientConfig(t, `{"template": "shop"}`), "/data/shop/deals", nil); rec.Code != http.StatusNotFound {
		t.Errorf("no deals page: %d", rec.Code)
	}
}
