package routes

import (
	"bytes"
	"context"
	"encoding/json"
	"math"
	"net/http"
	"net/http/httptest"
	"reflect"
	"strings"
	"testing"
	"time"

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

// testDirectoryListings are test data only: import lines shaped like the
// legacy DB export (41625316 and 37082064 copied from live localpages
// records; the others made up for paging and other cities).
const testDirectoryListings = `{"id":"41625316","business_name":"Ashburn Children's Dentistry - Dr. Lynda Dean-Duru","address":"44025 Pipeline Plaza","city":"Ashburn","state":"VA","zip":"20147","lat":"39.021595","lon":"-77.478088","phones":["(703) 723-8440 (Main)"],"category":"Pediatric Dentistry, Dentists","description":"At Ashburn Children's Dentistry we provide a full range of services including Laser dentistry for infants, children and teens, and patients with special needs. This allows us to deliver care.","email":"office@example.com","yext_id":"1528238"}
{"id":"37082064","business_name":"Apt Kolman P DMD","address":"44095  Pipeline Plz","city":"Ashburn","state":"VA","zip":"20147","lat":"39.022598","lon":"-77.475403","phones":[]}
{"id":"200","business_name":"Test Dental One","city":"Ashburn","state":"VA","category":"Dentists"}
{"id":"201","business_name":"Test Dental Two","city":"Ashburn","state":"VA","category":"Dentists"}
{"id":"300","business_name":"Alpha Plumbing","city":"Los Angeles","state":"CA","category":"Plumbers"}
{"id":"400","business_name":"Test Pizza Place","city":"Ashburn","state":"VA","zip":"20148","category":"Pizza","image":["https://cdn.example.test/pizza.jpg"],"business_hour":"Monday : 8:00 AM - 5:00 PM<br>Tuesday : Closed <br>","payment_options":"Cash, Visa"}
{"id":"401","business_name":"Test Thai Kitchen","city":"Sterling","state":"VA","lat":"39.0062","lon":"-77.4286","category":"Thai Restaurants"}
`

const testDirectoryConfig = `{
	"displayName": "Local Test",
	"template": "directory",
	"directory": {
		"defaultLocation": {"city": "Ashburn", "state": "VA"},
		"pageSize": 2,
		"nearbyCount": 5,
		"categories": [
			{"label": "Dentists", "slug": "dentists", "keyword": "dentists"},
			{"label": "Plumbers", "slug": "plumbers", "keyword": "plumbers"},
			{"label": "24 Hour Plumbers", "slug": "24-hour-plumbers", "keyword": "24 hour plumbers"},
			{"label": "Food & Dining", "slug": "food-and-dining", "keyword": "food and dining", "keywords": ["Pizza", "Thai Restaurants"]}
		],
		"seo": {"indexDetail": true, "indexState": true},
		"placeText": {"state": "full", "city": "intro"}
	},
	"google_adsense_account": "sites-2288675768043065",
	"sitemapPages": ["/", "/categories", "/states"],
	"seoMeta": {"listingCity": {"title": "{city} businesses | {displayName}"}},
	"legacyUrls": {"redirects": [
		{"from": "^/search/([A-Za-z]{2})/([^/]+)/([^/]+)$", "to": "/search?s=${3}&loc=${2},${1}"},
		{"from": "^/([a-z]{2})/([^/]+)/lpd-([0-9]+)-[^/]*\\.html$", "to": "/${1}/${2}/${3}"},
		{"from": "^/city/(.+)$", "to": "/va/${1}"},
		{"from": "^/find$", "to": "/search"},
		{"from": "^/business/([A-Za-z]+)$", "to": "/search?s=${1}"},
		{"from": "^/s/([A-Za-z]{2})/?$", "to": "/${1}"},
		{"from": "^/blogs/([^/]+)/?$", "to": "/articles/${1}"},
		{"from": "^/cat24$", "to": "/categories/24-hour-plumbers"}
	], "listings": ["^/business/([0-9]+)-[^/]*/?$", "^/biz/([^/]+)$"]}
}`

// testClientConfig builds a client config the way the middleware does: viper
// for the keys, the decoded JSON as Raw.
func testClientConfig(t *testing.T, configJSON string) *middlewares.ClientConfig {
	t.Helper()
	v := viper.New()
	v.SetConfigType("json")
	if err := v.ReadConfig(bytes.NewBufferString(configJSON)); err != nil {
		t.Fatal(err)
	}
	raw := map[string]interface{}{}
	if err := json.Unmarshal([]byte(configJSON), &raw); err != nil {
		t.Fatal(err)
	}
	return &middlewares.ClientConfig{ViperConfig: v, Raw: raw}
}

// useTestListings makes store the listings store for the test.
func useTestListings(t *testing.T, store listings.Store) {
	t.Helper()
	orig := listingsStore
	listingsStore = store
	t.Cleanup(func() { listingsStore = orig })
}

func testListingsStore(t *testing.T) listings.Store {
	t.Helper()
	store, err := listings.ReadJSONL(strings.NewReader(testDirectoryListings))
	if err != nil {
		t.Fatal(err)
	}
	return store
}

func serveWith(handler http.Handler, config *middlewares.ClientConfig, target string, params httprouter.Params) *httptest.ResponseRecorder {
	req := httptest.NewRequest(http.MethodGet, "https://localtest.com"+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
}

func TestParseDirectoryPath(t *testing.T) {
	settings := directorySettings{Categories: []directoryCategory{{Label: "24 Hour Plumbers", Slug: "24-hour-plumbers"}}}
	for _, tt := range []struct {
		path string
		want directoryPath
		ok   bool
	}{
		{"/va/ashburn", directoryPath{Kind: directoryCityPath, State: "va", CitySlug: "ashburn"}, true},
		{"/CA/Los Angeles/", directoryPath{Kind: directoryCityPath, State: "ca", CitySlug: "los-angeles"}, true},
		{"/ca/los+angeles/Hotels", directoryPath{Kind: directoryBrowsePath, State: "ca", CitySlug: "los-angeles", Slug: "hotels", Page: 1}, true},
		{"/ca/los-angeles/food & dining/3", directoryPath{Kind: directoryBrowsePath, State: "ca", CitySlug: "los-angeles", Slug: "food-and-dining", Page: 3}, true},
		{"/va/ashburn/24-hour-plumbers", directoryPath{Kind: directoryBrowsePath, State: "va", CitySlug: "ashburn", Slug: "24-hour-plumbers", Page: 1}, true},
		{"/va/ashburn/41625316-any-slug", directoryPath{Kind: directoryDetailPath, State: "va", CitySlug: "ashburn", ID: "41625316"}, true},
		{"/va/ashburn/41625316", directoryPath{Kind: directoryDetailPath, State: "va", CitySlug: "ashburn", ID: "41625316"}, true},
		{"/ca/los-angeles/lp-2742-z-dental-group", directoryPath{Kind: directoryDetailPath, State: "ca", CitySlug: "los-angeles", ID: "lp-2742"}, true},
		{"/ca/los-angeles/lp-2742", directoryPath{Kind: directoryDetailPath, State: "ca", CitySlug: "los-angeles", ID: "lp-2742"}, true},
		{"/ca/los-angeles/lp-dentists", directoryPath{Kind: directoryBrowsePath, State: "ca", CitySlug: "los-angeles", Slug: "lp-dentists", Page: 1}, true},
		{"/va", directoryPath{}, false},
		{"/va/ashburn/hotels/0", directoryPath{}, false},
		{"/va/ashburn/hotels/x", directoryPath{}, false},
		{"/va/ashburn/hotels/2/x", directoryPath{}, false},
		{"/va/ashburn/41625316-x/2", directoryPath{}, false},
		{"/va/!!!", directoryPath{}, false},
		{"/zz/ashburn", directoryPath{}, false},
	} {
		got, ok := parseDirectoryPath(tt.path, settings)
		if got != tt.want || ok != tt.ok {
			t.Errorf("parseDirectoryPath(%q) = %+v, %v; want %+v, %v", tt.path, got, ok, tt.want, tt.ok)
		}
	}
}

func TestDirectorySettingsFrom(t *testing.T) {
	got := directorySettingsFrom(testClientConfig(t, `{"template": "directory", "directory": {
		"defaultLocation": {"city": " Ashburn ", "state": "va"},
		"categories": [{"label": "Food & Dining"}, {"slug": "auto-repair"}, {"label": ""}]
	}}`))
	want := directorySettings{
		DefaultLocation: listings.Location{City: "Ashburn", State: "VA"},
		PageSize:        10,
		NearbyCount:     5,
		Categories: []directoryCategory{
			{Label: "Food & Dining", Slug: "food-and-dining", Keyword: "food and dining"},
			{Label: "Auto Repair", Slug: "auto-repair", Keyword: "auto repair"},
		},
	}
	if !reflect.DeepEqual(got, want) {
		t.Errorf("directorySettingsFrom:\n got %+v\nwant %+v", got, want)
	}
}

// TestDirectoryPages covers the directory URLs as the not-found handler
// serves them: canonical 301s, pages, 404s and their heads.
func TestDirectoryPages(t *testing.T) {
	useTestListings(t, testListingsStore(t))
	config := testClientConfig(t, testDirectoryConfig)
	handler := notFoundHandler(pageTemplatesFrom("../web/templates"))

	detail := "/va/ashburn/41625316-ashburn-childrens-dentistry-dr-lynda-dean-duru"
	for _, tt := range []struct {
		name     string
		path     string
		status   int
		location string   // redirects
		want     []string // in the page
	}{
		{"city page", "/va/ashburn", http.StatusOK, "", []string{
			"<title>Ashburn businesses | Local Test</title>", `content="noindex,follow"`,
			`<link rel="canonical" href="https://localtest.com/va/ashburn" />`, "singlecube.StaticPage", `"pageName":"listingCity"`,
			`"directory":{`,
		}},
		{"state in uppercase", "/VA/Ashburn", http.StatusMovedPermanently, "/va/ashburn", nil},
		{"trailing slash", "/va/ashburn/", http.StatusMovedPermanently, "/va/ashburn", nil},
		{"%20 in the city", "/ca/los%20angeles/plumbers", http.StatusMovedPermanently, "/ca/los-angeles/plumbers", nil},
		{"+ in the city", "/ca/los+angeles/plumbers", http.StatusMovedPermanently, "/ca/los-angeles/plumbers", nil},
		{"case and spaces, query kept", "/CA/Los%20Angeles/Plumbers?x=1", http.StatusMovedPermanently, "/ca/los-angeles/plumbers?x=1", nil},
		{"browse", "/va/ashburn/dentists", http.StatusOK, "", []string{
			"<title>Dentists in Ashburn, VA - Local Test</title>", `content="noindex,follow"`,
			`href="https://localtest.com/va/ashburn/dentists"`, `"pageName":"listingBrowse"`, "BreadcrumbList",
		}},
		{"browse page 2", "/va/ashburn/dentists/2", http.StatusOK, "", []string{
			"<title>Dentists in Ashburn, VA - Local Test - Page 2</title>", `href="https://localtest.com/va/ashburn/dentists/2"`,
		}},
		{"browse page 1", "/va/ashburn/dentists/1", http.StatusMovedPermanently, "/va/ashburn/dentists", nil},
		{"browse page 1 with a leading zero", "/va/ashburn/dentists/02", http.StatusMovedPermanently, "/va/ashburn/dentists/2", nil},
		{"browse past the last page", "/va/ashburn/dentists/3", http.StatusNotFound, "", nil},
		{"browse page 0", "/va/ashburn/dentists/0", http.StatusNotFound, "", nil},
		{"browse without results", "/ca/los-angeles/dentists", http.StatusOK, "", []string{"<title>Dentists in Los Angeles, CA - Local Test</title>"}},
		{"browse any slug", "/ca/los-angeles/alpha", http.StatusOK, "", []string{"<title>Alpha in Los Angeles, CA - Local Test</title>"}},
		{"browse any slug, other spelling", "/CA/Los-Angeles/Alpha", http.StatusMovedPermanently, "/ca/los-angeles/alpha", nil},
		{"browse a slug that finds nothing", "/ca/los-angeles/qwerty", http.StatusNotFound, "", nil},
		{"browse a junk slug, no redirect", "/ca/los-angeles/~qwerty", http.StatusNotFound, "", nil},
		{"browse a junk slug, page 1", "/ca/los-angeles/qwerty/1", http.StatusNotFound, "", nil},
		{"category slug starting with digits", "/va/ashburn/24-hour-plumbers", http.StatusOK, "", []string{"<title>24 Hour Plumbers in Ashburn, VA - Local Test</title>"}},
		{"too deep", "/va/ashburn/dentists/2/x", http.StatusNotFound, "", nil},
		{"state page", "/va", http.StatusOK, "", []string{
			"<title>Businesses in Virginia - Local Test</title>", `content="index,follow"`, `href="https://localtest.com/va"`,
			`"pageName":"listingState"`, `"name": "Virginia"`, `<meta name="google-adsense-account" content="sites-2288675768043065" />`,
		}},
		{"state in uppercase", "/VA", http.StatusMovedPermanently, "/va", nil},
		{"state, trailing slash", "/va/", http.StatusMovedPermanently, "/va", nil},
		{"state, uppercase and trailing slash, query kept", "/VA/?x=1", http.StatusMovedPermanently, "/va?x=1", nil},
		{"state without cities", "/wy", http.StatusNotFound, "", nil},
		{"state without cities, other spelling: no redirect", "/WY/", http.StatusNotFound, "", nil},
		{"category group browse", "/va/ashburn/food-and-dining", http.StatusOK, "", []string{
			"<title>Food &amp; Dining in Ashburn, VA - Local Test</title>", `"name": "Food \u0026 Dining"`,
		}},
		{"city without listings", "/va/nowhere", http.StatusNotFound, "", nil},
		{"city without listings, other spelling: no redirect", "/VA/Los+Angeles", http.StatusNotFound, "", nil},
		{"browse in a city without listings, other spelling: no redirect", "/CA/Nowhereville/dentists", http.StatusNotFound, "", nil},
		{"browse in a city without listings", "/va/nowhere/dentists", http.StatusNotFound, "", nil},
		{"detail", detail, http.StatusOK, "", []string{
			"<title>Ashburn Children&#39;s Dentistry - Dr. Lynda Dean-Duru - Ashburn, VA - Local Test</title>",
			`content="index,follow"`, `href="https://localtest.com` + detail + `"`, `"pageName":"listingDetail"`,
			`"@type": "LocalBusiness"`, `"telephone": "(703) 723-8440"`, `"@type": "GeoCoordinates"`, `"streetAddress": "44025 Pipeline Plaza"`,
			`"name": "Dentists"`, `"item": "https://localtest.com/va/ashburn/dentists"`, `"item": "https://localtest.com/va/ashburn"`,
		}},
		{"detail, wrong slug", "/va/ashburn/41625316-wrong", http.StatusMovedPermanently, detail, nil},
		{"detail, no slug", "/va/ashburn/41625316", http.StatusMovedPermanently, detail, nil},
		{"detail, wrong city and state", "/tx/austin/41625316-ashburn-childrens-dentistry-dr-lynda-dean-duru", http.StatusMovedPermanently, detail, nil},
		{"detail, case", "/VA/Ashburn/41625316-Ashburn-Childrens-Dentistry-Dr-Lynda-Dean-Duru", http.StatusMovedPermanently, detail, nil},
		{"detail, unknown id", "/va/ashburn/99999-nope", http.StatusNotFound, "", nil},
		{"detail with images and hours", "/va/ashburn/400-test-pizza-place", http.StatusOK, "", []string{
			`<meta property="og:image" content="https://cdn.example.test/pizza.jpg"`, `"image": [`, `"openingHours": [`, `"Mo 08:00-17:00"`,
			`"paymentAccepted": "Cash, Visa"`, "<title>Test Pizza Place - Ashburn, VA - Local Test</title>",
			`"item": "https://localtest.com/va/ashburn/food-and-dining"`, // Pizza is a Food & Dining keyword
		}},
		{"detail without a site category", "/va/ashburn/37082064-apt-kolman-p-dmd", http.StatusOK, "", []string{
			"<title>Apt Kolman P DMD - Ashburn, VA - Local Test</title>",
			`<meta name="description" content="Apt Kolman P DMD, 44095 Pipeline Plz, Ashburn, VA 20147." />`,
		}},
	} {
		t.Run(tt.name, func(t *testing.T) {
			rec := serveWith(handler, config, tt.path, nil)
			if rec.Code != tt.status {
				t.Fatalf("status = %d, want %d (Location %q)", rec.Code, tt.status, rec.Header().Get("Location"))
			}
			if tt.location != "" && rec.Header().Get("Location") != tt.location {
				t.Errorf("Location = %q, want %q", rec.Header().Get("Location"), tt.location)
			}
			if tt.status == http.StatusMovedPermanently && rec.Header().Get("Cache-Control") != seoRedirectCacheControl {
				t.Errorf("redirect Cache-Control = %q", rec.Header().Get("Cache-Control"))
			}
			html := rec.Body.String()
			if tt.status == http.StatusNotFound {
				if !strings.Contains(html, "<title>Page not found - Local Test</title>") || strings.Contains(html, `rel="canonical"`) ||
					rec.Header().Get("X-Robots-Tag") != "noindex, nofollow" {
					t.Errorf("want the site's noindex not-found page, got X-Robots-Tag %q", rec.Header().Get("X-Robots-Tag"))
				}
			}
			for _, want := range tt.want {
				if !strings.Contains(html, want) {
					t.Errorf("page is missing %s", want)
				}
			}
			if strings.Contains(html, "office@example.com") {
				t.Error("page exposes the listing's email")
			}
		})
	}

	// The listing description, cut on a word, is the detail page's description.
	html := serveWith(handler, config, detail, nil).Body.String()
	want := `<meta name="description" content="At Ashburn Children&#39;s Dentistry we provide a full range of services including Laser dentistry for infants, children and teens, and patients with special" />`
	if !strings.Contains(html, want) {
		t.Errorf("detail description: want %s", want)
	}
	if !strings.Contains(serveWith(handler, config, "/va/ashburn/37082064-apt-kolman-p-dmd", nil).Body.String(), "GeoCoordinates") {
		t.Error("listing with coordinates: want geo")
	}
}

func TestDirectoryPages_ListingsUnavailable(t *testing.T) {
	useTestListings(t, listings.Disabled{})
	config := testClientConfig(t, testDirectoryConfig)
	tpl := pageTemplatesFrom("../web/templates")
	handler := notFoundHandler(tpl)
	search := directorySearchHandler(http.NotFoundHandler(), tpl)
	states := directoryStatesHandler(http.NotFoundHandler(), tpl)

	for _, tt := range []struct {
		handler http.Handler
		path    string
	}{
		{handler, "/va/ashburn"},
		{handler, "/va"},
		{states, "/states"},
		{handler, "/va/ashburn/dentists"},
		{handler, "/va/ashburn/41625316-ashburn-childrens-dentistry-dr-lynda-dean-duru"},
		{search, "/search?s=dentists"},
	} {
		rec := serveWith(tt.handler, config, tt.path, nil)
		html := rec.Body.String()
		if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "3600" || rec.Header().Get("X-Robots-Tag") != "noindex, nofollow" {
			t.Errorf("%s: status %d, Retry-After %q, X-Robots-Tag %q; want 503, 3600, noindex", tt.path, rec.Code, rec.Header().Get("Retry-After"), rec.Header().Get("X-Robots-Tag"))
		}
		if !strings.Contains(html, "singlecube.StaticPage") || strings.Contains(html, `rel="canonical"`) || strings.Contains(html, "BreadcrumbList") {
			t.Errorf("%s: want the page shell without canonical or structured data", tt.path)
		}
	}
	// A canonical redirect doesn't need the store.
	for _, path := range []string{"/VA/Ashburn", "/VA"} {
		if rec := serveWith(handler, config, path, nil); rec.Code != http.StatusMovedPermanently {
			t.Errorf("%s while unavailable: %d, want 301", path, rec.Code)
		}
	}
}

// TestDirectoryPaths_OtherSites checks that state-code paths on other sites
// keep the article/category routing.
func TestDirectoryPaths_OtherSites(t *testing.T) {
	useTestListings(t, testListingsStore(t))
	orig := cmsService
	cmsService = nil // the CMS can't tell, so the category page is served
	t.Cleanup(func() { cmsService = orig })

	handler := notFoundHandler(pageTemplatesFrom("../web/templates"))
	for _, template := range []string{"magazine", "editorial", ""} {
		config := testClientConfig(t, `{"displayName": "Other", "template": "`+template+`"}`)
		rec := serveWith(handler, config, "/ca/foo", nil)
		if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "singlecube.ArticleList") {
			t.Errorf("%q site: /ca/foo = %d, want the category page", template, rec.Code)
		}
		if serveDirectoryPath(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/va/ashburn", nil).WithContext(
			context.WithValue(context.Background(), middlewares.ClientConfigKey, config)), pageTemplatesFrom("../web/templates")) {
			t.Errorf("%q site: serveDirectoryPath handled /va/ashburn", template)
		}
	}
}

func TestDirectorySearchHandler(t *testing.T) {
	useTestListings(t, testListingsStore(t))
	config := testClientConfig(t, testDirectoryConfig)
	articleSearch := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := directorySearchHandler(articleSearch, pageTemplatesFrom("../web/templates"))

	for _, tt := range []struct {
		name     string
		target   string
		status   int
		location string
		want     []string
	}{
		{"legacy search=", "/search?search=dentists&loc=Ashburn,VA", http.StatusMovedPermanently, "/search?s=dentists&loc=Ashburn,VA", nil},
		{"legacy keyword=", "/search?keyword=dentists", http.StatusMovedPermanently, "/search?s=dentists", nil},
		{"legacy q=", "/search?q=dentists&page=2", http.StatusMovedPermanently, "/search?s=dentists&page=2", nil},
		{"results", "/search?s=dentists&loc=ashburn,va", http.StatusOK, "", []string{
			"<title>Dentists in Ashburn, VA - Local Test</title>", `<meta name="robots" content="noindex,follow" />`,
			`href="https://localtest.com/search?loc=Ashburn%2C&#43;VA&amp;s=dentists"`, `"pageName":"listingResults"`,
		}},
		{"default location", "/search?s=dentists&loc=Delhi,DL", http.StatusOK, "", []string{"<title>Dentists in Ashburn, VA - Local Test</title>"}},
		{"city without listings, as typed", "/search?s=plumbers&loc=Austin,%20TX", http.StatusOK, "", []string{"<title>Plumbers in Austin, TX - Local Test</title>"}},
		{"unresolvable location: default", "/search?s=plumbers&loc=nowhere-at-all", http.StatusOK, "", []string{"<title>Plumbers in Ashburn, VA - Local Test</title>"}},
		{"ST,City/ location", "/search?s=plumbers&loc=CA,Los+Angeles/", http.StatusOK, "", []string{"<title>Plumbers in Los Angeles, CA - Local Test</title>"}},
		{"zip location", "/search?s=pizza&loc=20148", http.StatusOK, "", []string{"<title>Pizza in Ashburn, VA - Local Test</title>"}},
		{"category label", "/search?s=food+%26+dining", http.StatusOK, "", []string{"<title>Food &amp; Dining in Ashburn, VA - Local Test</title>"}},
		{"category slug", "/search?s=Food-And-Dining", http.StatusOK, "", []string{"<title>Food &amp; Dining in Ashburn, VA - Local Test</title>"}},
		{"no keyword", "/search", http.StatusOK, "", []string{"<title>Businesses in Ashburn, VA - Local Test</title>"}},
		{"page 2", "/search?s=dentists&page=2", http.StatusOK, "", []string{"page=2"}},
		{"past the last page", "/search?s=dentists&page=5", http.StatusNotFound, "", nil},
		{"the largest page", "/search?s=dentists&page=9223372036854775807", http.StatusNotFound, "", nil},
		{"a page too big for an int", "/search?s=food+%26+dining&page=99999999999999999999", http.StatusNotFound, "", nil},
		{"a page that isn't a number: page 1", "/search?s=dentists&page=x", http.StatusOK, "", []string{"<title>Dentists in Ashburn, VA - Local Test</title>"}},
	} {
		t.Run(tt.name, func(t *testing.T) {
			rec := serveWith(handler, config, tt.target, nil)
			if rec.Code != tt.status {
				t.Fatalf("status = %d, want %d", rec.Code, tt.status)
			}
			if tt.location != "" && rec.Header().Get("Location") != tt.location {
				t.Errorf("Location = %q, want %q", rec.Header().Get("Location"), tt.location)
			}
			for _, want := range tt.want {
				if !strings.Contains(rec.Body.String(), want) {
					t.Errorf("page is missing %s", want)
				}
			}
		})
	}

	// Other sites keep the article search, with its own legacy rename.
	other := testClientConfig(t, `{"displayName": "Other", "template": "magazine"}`)
	if rec := serveWith(handler, other, "/search?search=x", nil); rec.Code != http.StatusTeapot {
		t.Errorf("magazine site: %d, want the article search", rec.Code)
	}
	if query, ok := legacySearchRedirectQuery("search=x&page=2"); !ok || query != "term=x&page=2" {
		t.Errorf("article search rename = %q, %v", query, ok)
	}
}

func TestDirectoryCategoriesHandler(t *testing.T) {
	other := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := directoryCategoriesHandler(other, pageTemplatesFrom("../web/templates"))

	rec := serveWith(handler, testClientConfig(t, testDirectoryConfig), "/categories", nil)
	html := rec.Body.String()
	for _, want := range []string{"<title>Categories - Local Test</title>", `content="index,follow"`, `href="https://localtest.com/categories"`, `"pageName":"categories"`} {
		if !strings.Contains(html, want) {
			t.Errorf("categories page is missing %s", want)
		}
	}
	if rec := serveWith(handler, testClientConfig(t, `{"template": "magazine"}`), "/categories", nil); rec.Code != http.StatusTeapot {
		t.Errorf("magazine site: %d, want it routed as before", rec.Code)
	}
}

func TestDirectoryStaticPages(t *testing.T) {
	raw := map[string]interface{}{"template": "directory", "pages": map[string]interface{}{"contactUs": map[string]interface{}{"content": map[string]interface{}{"title": "Contact"}}}}
	if !usesSiteTemplate(raw) || !servesConfiguredPage(raw, "contactUs", true) || servesConfiguredPage(raw, "forAdvertisers", true) {
		t.Error("directory sites: want configured pages served, others 404")
	}
	if got := siteTemplatePageLabel(map[string]interface{}{"template": "directory"}, notFoundPageName); got != "Page not found" {
		t.Errorf("not-found title = %q", got)
	}
}

func TestDataListingsHandler(t *testing.T) {
	useTestListings(t, testListingsStore(t))
	config := testClientConfig(t, testDirectoryConfig)
	handler := DataListingsHandler()
	get := func(config *middlewares.ClientConfig, id, query string) (*httptest.ResponseRecorder, map[string]interface{}) {
		t.Helper()
		rec := serveWith(handler, config, "/data/listings/"+id+query, httprouter.Params{{Key: "id", Value: id}})
		body := map[string]interface{}{}
		if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
			t.Fatalf("%s%s: %v", id, query, err)
		}
		return rec, body
	}
	ids := func(v interface{}) []string {
		out := []string{}
		for _, item := range v.([]interface{}) {
			out = append(out, item.(map[string]interface{})["id"].(string))
		}
		return out
	}

	rec, body := get(config, "search", "?s=dentists&loc=Ashburn,%20VA")
	if rec.Code != http.StatusOK || rec.Header().Get("Cache-Control") != "public, max-age=600" {
		t.Fatalf("search: %d %q", rec.Code, rec.Header().Get("Cache-Control"))
	}
	wantLocation := map[string]interface{}{"city": "Ashburn", "state": "VA", "label": "Ashburn, VA", "path": "/va/ashburn"}
	if body["keyword"] != "dentists" || !reflect.DeepEqual(body["location"], wantLocation) || body["total"] != 3.0 || body["page"] != 1.0 ||
		body["pageSize"] != 2.0 || body["totalPages"] != 2.0 || !reflect.DeepEqual(ids(body["listings"]), []string{"41625316", "200"}) {
		t.Errorf("search: %v", body)
	}
	first := body["listings"].([]interface{})[0].(map[string]interface{})
	for _, key := range []string{"id", "name", "url", "address", "city", "state", "zip", "lat", "lon", "phones", "website", "categories",
		"description", "hours", "paymentOptions", "specialOffer", "images", "source"} {
		if _, ok := first[key]; !ok {
			t.Errorf("listing has no %q", key)
		}
	}
	if _, ok := first["email"]; ok {
		t.Error("listing exposes email")
	}

	if _, body := get(config, "search", "?s=dentists&loc=Delhi,%20DL&page=2"); body["location"].(map[string]interface{})["label"] != "Ashburn, VA" ||
		!reflect.DeepEqual(ids(body["listings"]), []string{"201"}) {
		t.Errorf("unparseable loc, page 2: %v", body)
	}
	if _, body := get(config, "search", "?loc=los-angeles,ca"); body["location"].(map[string]interface{})["city"] != "Los Angeles" || body["total"] != 1.0 {
		t.Errorf("hyphenated city: %v", body)
	}
	if _, body := get(config, "search", "?s=dentists&loc=Ashburn,%20VA&pageSize=1"); body["pageSize"] != 1.0 || body["totalPages"] != 3.0 ||
		!reflect.DeepEqual(ids(body["listings"]), []string{"41625316"}) {
		t.Errorf("pageSize=1: %v", body)
	}
	// A page past the last, however big, is an empty page.
	for _, page := range []string{"5", "9223372036854775807", "99999999999999999999"} {
		if rec, body := get(config, "search", "?s=dentists&loc=Ashburn,%20VA&page="+page); rec.Code != http.StatusOK || len(ids(body["listings"])) != 0 ||
			body["total"] != 3.0 || body["totalPages"] != 2.0 {
			t.Errorf("page=%s: %d %v", page, rec.Code, body)
		}
	}
	for _, size := range []string{"5", "0", "x"} {
		if _, body := get(config, "search", "?s=dentists&loc=Ashburn,%20VA&pageSize="+size); body["pageSize"] != 2.0 {
			t.Errorf("pageSize=%s: page size %v, want the site's 2", size, body["pageSize"])
		}
	}

	rec, body = get(config, "41625316", "")
	if rec.Code != http.StatusOK || body["listing"].(map[string]interface{})["id"] != "41625316" ||
		!reflect.DeepEqual(ids(body["nearby"]), []string{"200", "201"}) {
		t.Errorf("listing: %d %v", rec.Code, body)
	}
	if _, body := get(config, "37082064", ""); !reflect.DeepEqual(ids(body["nearby"]), []string{}) {
		t.Errorf("listing without categories: nearby %v, want []", body["nearby"])
	}
	for _, id := range []string{"99999", "abc"} {
		if rec, body := get(config, id, ""); rec.Code != http.StatusNotFound || body["error"] != "not_found" || rec.Header().Get("Cache-Control") != listingsCacheControl {
			t.Errorf("%s: %d %v %q", id, rec.Code, body, rec.Header().Get("Cache-Control"))
		}
	}
	if rec, body := get(testClientConfig(t, `{"template": "magazine"}`), "41625316", ""); rec.Code != http.StatusNotFound || body["error"] != "not_found" {
		t.Errorf("magazine site: %d %v", rec.Code, body)
	}

	useTestListings(t, listings.Disabled{})
	for _, id := range []string{"search", "41625316"} {
		rec, body := get(config, id, "")
		if rec.Code != http.StatusServiceUnavailable || body["error"] != "listings_unavailable" || rec.Header().Get("Cache-Control") != "no-store" {
			t.Errorf("%s while unavailable: %d %v %q", id, rec.Code, body, rec.Header().Get("Cache-Control"))
		}
	}
}

func TestLegacyURLMiddleware_Directory(t *testing.T) {
	useTestListings(t, testListingsStore(t))
	config := testClientConfig(t, testDirectoryConfig)
	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := legacyURLMiddleware(next, pageTemplatesFrom("../web/templates"))

	for path, want := range map[string]string{
		"/search/TX/Austin/dentists":                 "/search?s=dentists&loc=Austin,TX",
		"/find?search=dentists":                      "/search?s=dentists",
		"/va/ashburn/lpd-41625316-old-slug.html":     "/va/ashburn/41625316-ashburn-childrens-dentistry-dr-lynda-dean-duru",
		"/tx/austin/lpd-41625316-old-slug.html":      "/va/ashburn/41625316-ashburn-childrens-dentistry-dr-lynda-dean-duru",
		"/city/Ashburn":                              "/va/ashburn",
		"/city/Ashburn/Dentists/1":                   "/va/ashburn/dentists",
		"/va/ashburn/lpd-99999-unknown-listing.html": "/va/ashburn/99999",
		// A state target lands on the lowercase state page in one hop.
		"/s/VA/": "/va",
		"/s/va":  "/va",
		// Not an article: /categories/{slug} is its own route.
		"/cat24": "/categories/24-hour-plumbers",
	} {
		rec := serveWith(handler, config, path, nil)
		if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != want {
			t.Errorf("%s: %d %q, want 301 %q", path, rec.Code, rec.Header().Get("Location"), want)
		}
	}

	// A target that is no page is a 404 here, not a 301 to one.
	for _, path := range []string{
		"/s/WY",                      // a state without cities
		"/city/Nowhere",              // a city without listings
		"/city/Nowhere/Dentists",     // browse in a city without listings
		"/city/Ashburn/qwerty",       // a slug that isn't a category and finds nothing
		"/city/Los%20Angeles/qwerty", // %20 in the target, a city without listings
	} {
		rec := serveWith(handler, config, path, nil)
		if rec.Code != http.StatusNotFound || rec.Header().Get("X-Robots-Tag") != "noindex, nofollow" {
			t.Errorf("%s: %d %q, want the 404 page", path, rec.Code, rec.Header().Get("Location"))
		}
	}

	// Store unavailable: still redirected.
	useTestListings(t, listings.Disabled{})
	for path, want := range map[string]string{
		"/s/WY":         "/wy",
		"/city/Nowhere": "/va/nowhere",
	} {
		rec := serveWith(handler, config, path, nil)
		if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != want {
			t.Errorf("%s while unavailable: %d %q, want 301 %q", path, rec.Code, rec.Header().Get("Location"), want)
		}
	}
}

// TestLegacyURLMiddleware_ArticleTargets: on a directory site a legacy
// redirect to an article URL goes to the article's canonical URL in one hop;
// one to no article is a 404 (or the deleted article's listing). Other sites
// redirect to the target as it is.
func TestLegacyURLMiddleware_ArticleTargets(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		switch r.URL.Query().Get("action") {
		case "getcategories":
			w.Write([]byte(`{"data":{"localtest.com":[{"cat_id":"1","cat_name":"News"},{"cat_id":"2","cat_name":"Articles"}],"other.com":[{"cat_id":"3","cat_name":"Tennis"}]}}`))
		case "getcategoryarticles":
			w.Write([]byte(`{"data":[]}`))
		case "getarticledata":
			switch r.URL.Query().Get("id") {
			case "77":
				w.Write([]byte(`{"data":{"id":"77","title":"Hello World","slug_title":"Hello World","category":"News"}}`))
			case "37":
				w.Write([]byte(`{"data":{"id":"37","title":"Serve","category":"Tennis"}}`)) // other.com's
			case "500":
				w.WriteHeader(http.StatusInternalServerError)
			default:
				w.Write([]byte(`{"data": false}`))
			}
		}
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()
	useTestListings(t, testListingsStore(t))

	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := legacyURLMiddleware(next, pageTemplatesFrom("../web/templates"))
	directory := testClientConfig(t, testDirectoryConfig)
	editorial := testClientConfig(t, strings.Replace(testDirectoryConfig, `"template": "directory"`, `"template": "editorial"`, 1))
	for _, tt := range []struct {
		name     string
		config   *middlewares.ClientConfig
		path     string
		status   int
		location string
	}{
		{"old slug, other category", directory, "/blogs/77-old-slug", http.StatusMovedPermanently, "/news/77-hello-world"},
		{"no slug, query kept", directory, "/blogs/77?x=1", http.StatusMovedPermanently, "/news/77-hello-world?x=1"},
		{"editorial site: the target as it is", editorial, "/blogs/77-old-slug/", http.StatusMovedPermanently, "/articles/77-old-slug"},
		{"editorial site, another site's article: as main", editorial, "/blogs/37-serve", http.StatusMovedPermanently, "/articles/37-serve"},
		{"deleted article: its listing", directory, "/blogs/88-gone", http.StatusMovedPermanently, "/articles"},
		{"another site's article", directory, "/blogs/37-serve", http.StatusNotFound, ""},
		{"not an article ID", directory, "/blogs/12x-junk", http.StatusNotFound, ""},
		{"CMS request failed: as the rule says", directory, "/blogs/500-x", http.StatusMovedPermanently, "/articles/500-x"},
	} {
		t.Run(tt.name, func(t *testing.T) {
			rec := serveWith(handler, tt.config, tt.path, nil)
			if rec.Code != tt.status || rec.Header().Get("Location") != tt.location {
				t.Fatalf("%d %q, want %d %q", rec.Code, rec.Header().Get("Location"), tt.status, tt.location)
			}
			if tt.status == http.StatusMovedPermanently && rec.Header().Get("Cache-Control") != seoRedirectCacheControl {
				t.Errorf("redirect Cache-Control = %q", rec.Header().Get("Cache-Control"))
			}
			if tt.status == http.StatusNotFound && rec.Header().Get("X-Robots-Tag") != "noindex, nofollow" {
				t.Errorf("404 X-Robots-Tag = %q", rec.Header().Get("X-Robots-Tag"))
			}
		})
	}
}

// A slow CMS can't hold a legacy redirect past legacyArticleLookupTimeout: it
// goes to the plain target.
func TestLegacyURLMiddleware_ArticleTargetTimeout(t *testing.T) {
	release := make(chan struct{})
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		<-release
		w.Write([]byte(`{"data": false}`))
	}))
	defer srv.Close()
	defer close(release)
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()
	useTestListings(t, testListingsStore(t))

	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := legacyURLMiddleware(next, pageTemplatesFrom("../web/templates"))
	start := time.Now()
	rec := serveWith(handler, testClientConfig(t, testDirectoryConfig), "/blogs/66-slow", nil)
	if elapsed := time.Since(start); elapsed > legacyArticleLookupTimeout+time.Second {
		t.Errorf("took %v", elapsed)
	}
	if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/articles/66-slow" {
		t.Errorf("%d %q, want 301 /articles/66-slow", rec.Code, rec.Header().Get("Location"))
	}
}

func TestArticleRouteParams(t *testing.T) {
	for _, tt := range []struct {
		path string
		want httprouter.Params
	}{
		{"/articles/77-x", httprouter.Params{{Key: "category", Value: "articles"}, {Key: "slug", Value: "77-x"}}},
		{"/news/tips/77-x/", httprouter.Params{{Key: "category", Value: "news"}, {Key: "subcategory", Value: "tips"}, {Key: "slug", Value: "77-x"}}},
		{"/article/77-x", httprouter.Params{{Key: "slug", Value: "77-x"}}},
		{"/categories/24-hour-plumbers", nil},
		{"/info/1", nil},
		{"/shop/product-details/123/x", nil},
		{"/articles/category/1", nil},
		{"/articles", nil},
		{"/news/x", nil},
	} {
		got, ok := articleRouteParams(tt.path)
		if !reflect.DeepEqual(got, tt.want) || ok != (tt.want != nil) {
			t.Errorf("articleRouteParams(%q) = %v, %v; want %v", tt.path, got, ok, tt.want)
		}
	}
}

func TestListingsPageParam(t *testing.T) {
	for raw, want := range map[string]int{
		"": 1, "x": 1, "0": 1, "-3": 1, "-99999999999999999999": 1, "2": 2,
		"9223372036854775807": math.MaxInt, "99999999999999999999": math.MaxInt,
	} {
		if got := listingsPageParam(raw); got != want {
			t.Errorf("listingsPageParam(%q) = %d, want %d", raw, got, want)
		}
	}
}

// A config's directory settings are read once: its category groups compile
// once, not per request.
func TestDirectorySettingsFrom_Cached(t *testing.T) {
	config := testClientConfig(t, testDirectoryConfig)
	first, _ := directorySettingsFrom(config).category("food-and-dining")
	again, _ := directorySettingsFrom(config).category("food-and-dining")
	if first.group == nil || first.group != again.group {
		t.Errorf("group filter compiled again: %p, %p", first.group, again.group)
	}
	// Another config's block is another entry.
	other, _ := directorySettingsFrom(testClientConfig(t, testDirectoryConfig)).category("food-and-dining")
	if other.group == first.group {
		t.Error("two configs share one cache entry")
	}
	if got := directorySettingsFrom(nil); got.PageSize != listings.DefaultPageSize || got.Categories != nil {
		t.Errorf("no config: %+v", got)
	}
}

func TestListingCategory(t *testing.T) {
	settings := directorySettingsFrom(testClientConfig(t, testDirectoryConfig))
	for _, tt := range []struct {
		name    string
		listing listings.Listing
		want    string // the category's slug, "" for none
	}{
		{"category equals a label", listings.Listing{Name: "A", Categories: []string{"Dentists"}}, "dentists"},
		{"category equals a keyword, any case", listings.Listing{Name: "A", Categories: []string{"24 HOUR PLUMBERS"}}, "24-hour-plumbers"},
		// accoona 16673186 Pizza Time: Pizza is a Food & Dining keyword.
		{"a group keyword", listings.Listing{Name: "Pizza Time", Categories: []string{"American Restaurants", "Pizza", "Sandwich Shops"}}, "food-and-dining"},
		{"every word of a group keyword, any order", listings.Listing{Name: "B", Categories: []string{"Restaurants (Thai)"}}, "food-and-dining"},
		{"a group keyword inside a word", listings.Listing{Name: "B", Categories: []string{"Mozzapizza Salon"}}, ""},
		{"a group keyword in the name, as search finds it", listings.Listing{Name: "Pizza Corner", Categories: []string{"Caterers"}}, "food-and-dining"},
		{"the record's group", listings.Listing{Name: "C", Categories: []string{"Diners"}, Group: "food & dining"}, "food-and-dining"},
		{"an exact match wins over an earlier group", listings.Listing{Name: "Pizza Dental", Categories: []string{"Dentists"}}, "dentists"},
		{"no match", listings.Listing{Name: "D", Categories: []string{"Thai Massage"}}, ""},
	} {
		c, ok := settings.listingCategory(tt.listing)
		if c.Slug != tt.want || ok != (tt.want != "") {
			t.Errorf("%s: %q %v, want %q", tt.name, c.Slug, ok, tt.want)
		}
	}
}

func TestListingMeta(t *testing.T) {
	tokens := listingMetaTokens{Keyword: "pet groomers", Location: "Ashburn, VA", City: "Ashburn", State: "VA", Name: "Shop", Category: "Pets", Page: 2, DisplayName: "Site"}
	if got := expandListingPattern("{Keyword}|{keyword}|{location}|{city}|{state}|{name}|{category}|{page}|{displayName}", tokens); got != "Pet Groomers|pet groomers|Ashburn, VA|Ashburn|VA|Shop|Pets|2|Site" {
		t.Errorf("expandListingPattern = %q", got)
	}
	for _, tt := range []struct {
		in   string
		max  int
		want string
	}{
		{"short text", 155, "short text"},
		{"one two three", 9, "one two"},
		{"one two three", 7, "one two"},
		{"one, two", 5, "one"},
	} {
		if got := cutOnWord(tt.in, tt.max); got != tt.want {
			t.Errorf("cutOnWord(%q, %d) = %q, want %q", tt.in, tt.max, got, tt.want)
		}
	}
	if got := listingDescription(listings.Listing{Name: "A {name}", City: "Ashburn", State: "VA"}); got != "A name, Ashburn, VA." {
		t.Errorf("listingDescription = %q", got)
	}

	// The browse title takes the page from page 2, unless the site's pattern places it.
	config := testClientConfig(t, `{"seoMeta": {"listingBrowse": {"title": "{Keyword} near {city}, page {page}"}}}`)
	p := directoryPath{Kind: directoryBrowsePath, Page: 2}
	if title, _ := directoryPathMeta(config, p, tokens); title != "Pet Groomers near Ashburn, page 2" {
		t.Errorf("custom browse title = %q", title)
	}
	if title, description := directoryPathMeta(testClientConfig(t, `{}`), p, tokens); title != "Pet Groomers in Ashburn, VA - Site - Page 2" || description != title {
		t.Errorf("default browse title = %q, description %q", title, description)
	}
}

func TestLocalBusinessJSONLD(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "https://localtest.com/x", nil)
	got := string(localBusinessJSONLD(req, listings.Listing{Name: "Alpha Plumbing", URL: "/ca/los-angeles/300-alpha-plumbing", City: "Los Angeles", State: "CA"}))
	for _, want := range []string{`"@type": "LocalBusiness"`, `"url": "https://localtest.com/ca/los-angeles/300-alpha-plumbing"`, `"addressLocality": "Los Angeles"`} {
		if !strings.Contains(got, want) {
			t.Errorf("LocalBusiness is missing %s", want)
		}
	}
	for _, unwanted := range []string{"geo", "telephone", "streetAddress", "postalCode"} {
		if strings.Contains(got, unwanted) {
			t.Errorf("LocalBusiness has %s for a listing without one", unwanted)
		}
	}

	// The WebSite search action uses the directory search param.
	if site := string(websiteJSONLD(testClientConfig(t, testDirectoryConfig), req)); !strings.Contains(site, "/search?s={search_term_string}") {
		t.Errorf("directory WebSite schema: %s", site)
	}
	if site := string(websiteJSONLD(testClientConfig(t, `{"displayName": "Other"}`), req)); !strings.Contains(site, "/search?term={search_term_string}") {
		t.Errorf("other WebSite schema: %s", site)
	}
}

func TestRenameQueryParam(t *testing.T) {
	for _, tt := range []struct {
		query string
		want  string
		ok    bool
	}{
		{"search=a&loc=X", "s=a&loc=X", true},
		{"loc=X&q=a%20b", "loc=X&s=a%20b", true},
		{"keyword=a&search=b", "s=a", true},
		{"s=a&search=b", "", false},
		{"loc=X", "", false},
		{"search=%zz", "", false},
	} {
		got, ok := directorySearchRedirectQuery(tt.query)
		if got != tt.want || ok != tt.ok {
			t.Errorf("directorySearchRedirectQuery(%q) = %q, %v; want %q, %v", tt.query, got, ok, tt.want, tt.ok)
		}
	}
}

func TestDirectorySettingsFrom_Batch2Keys(t *testing.T) {
	got := directorySettingsFrom(testClientConfig(t, `{"template": "directory", "directory": {
		"radiusMiles": 15,
		"categories": [{"label": "Food & Dining", "keyword": "food and dining", "keywords": [" Pizza ", "", 3, "Thai Restaurants"]}],
		"seo": {"indexState": true, "indexCategory": true},
		"placeText": {"state": "full", "city": "intro"}
	}}`))
	want := directorySettings{
		PageSize:    10,
		NearbyCount: 5,
		Categories: []directoryCategory{
			{Label: "Food & Dining", Slug: "food-and-dining", Keyword: "food and dining", Keywords: []string{"Pizza", "Thai Restaurants"}},
		},
		RadiusMiles:    15,
		IndexState:     true,
		IndexCategory:  true,
		PlaceTextState: "full",
		PlaceTextCity:  "intro",
	}
	// The group's filter is compiled with the settings.
	if got.Categories[0].group == nil || !got.Categories[0].group.Matches(listings.Listing{Name: "Pizza Time"}) {
		t.Errorf("category group filter = %v", got.Categories[0].group)
	}
	got.Categories[0].group = nil
	if !reflect.DeepEqual(got, want) {
		t.Errorf("directorySettingsFrom:\n got %+v\nwant %+v", got, want)
	}
	for _, raw := range []string{`{"radiusMiles": -1, "placeText": {"state": "all", "city": "full"}}`, `{"radiusMiles": "15", "placeText": "intro"}`} {
		got := directorySettingsFrom(testClientConfig(t, `{"directory": `+raw+`}`))
		if got.RadiusMiles != 0 || got.PlaceTextState != "" || got.PlaceTextCity != "" {
			t.Errorf("%s: want no radius or place text, got %+v", raw, got)
		}
	}

	// The search keyword that names a category, and the group query.
	settings := directorySettingsFrom(testClientConfig(t, testDirectoryConfig))
	for keyword, want := range map[string]string{"food & dining": "food-and-dining", "FOOD-AND-DINING": "food-and-dining", "Food And Dining": "food-and-dining", "dentists": "dentists", "pizza": "", "": ""} {
		if c, _ := settings.categoryNamed(keyword); c.Slug != want {
			t.Errorf("categoryNamed(%q) = %q, want %q", keyword, c.Slug, want)
		}
	}
	food, _ := settings.category("food-and-dining")
	q := settings.listingQuery("food & dining", food, true, listings.Location{City: "Ashburn", State: "VA"})
	if q.Keyword != "" || !reflect.DeepEqual(q.AnyOf, []string{"Pizza", "Thai Restaurants", "food and dining"}) || q.Group != "Food & Dining" {
		t.Errorf("group query = %+v", q)
	}
	dentists, _ := settings.category("dentists")
	if q := settings.listingQuery("dentists", dentists, true, listings.Location{}); q.Keyword != "dentists" || q.AnyOf != nil || q.Group != "" {
		t.Errorf("keyword category query = %+v", q)
	}
}

func TestDataListingsHandler_Batch2(t *testing.T) {
	useTestListings(t, testListingsStore(t))
	config := testClientConfig(t, testDirectoryConfig)
	handler := DataListingsHandler()
	get := func(config *middlewares.ClientConfig, id, query string) (*httptest.ResponseRecorder, map[string]interface{}) {
		t.Helper()
		rec := serveWith(handler, config, "/data/listings/"+id+query, httprouter.Params{{Key: "id", Value: id}})
		body := map[string]interface{}{}
		if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
			t.Fatalf("%s%s: %v", id, query, err)
		}
		return rec, body
	}
	ids := func(v interface{}) []string {
		out := []string{}
		for _, item := range v.([]interface{}) {
			out = append(out, item.(map[string]interface{})["id"].(string))
		}
		return out
	}

	rec, body := get(config, "states", "")
	wantStates := []interface{}{
		map[string]interface{}{"code": "CA", "name": "California", "path": "/ca", "count": 1.0},
		map[string]interface{}{"code": "VA", "name": "Virginia", "path": "/va", "count": 6.0},
	}
	if rec.Code != http.StatusOK || rec.Header().Get("Cache-Control") != listingsCacheControl || !reflect.DeepEqual(body["states"], wantStates) {
		t.Errorf("states: %d %q %v", rec.Code, rec.Header().Get("Cache-Control"), body)
	}

	rec, body = get(config, "cities", "?state=VA")
	wantCities := map[string]interface{}{
		"state": map[string]interface{}{"code": "VA", "name": "Virginia", "path": "/va"},
		"cities": []interface{}{
			map[string]interface{}{"name": "Ashburn", "slug": "ashburn", "path": "/va/ashburn", "count": 5.0},
			map[string]interface{}{"name": "Sterling", "slug": "sterling", "path": "/va/sterling", "count": 1.0},
		},
	}
	if rec.Code != http.StatusOK || !reflect.DeepEqual(body, wantCities) {
		t.Errorf("cities: %d %v", rec.Code, body)
	}
	for _, query := range []string{"?state=wy", "?state=zz", "", "?state=../va"} {
		if rec, body := get(config, "cities", query); rec.Code != http.StatusNotFound || body["error"] != "not_found" || rec.Header().Get("Cache-Control") != listingsCacheControl {
			t.Errorf("cities%s: %d %v %q, want 404, cached", query, rec.Code, body, rec.Header().Get("Cache-Control"))
		}
	}

	// A category group: any of its terms, in the exact city without a radius.
	_, body = get(config, "search", "?s=Food+%26+Dining&loc=VA,Ashburn/")
	if body["category"] != "food-and-dining" || body["keyword"] != "Food & Dining" || !reflect.DeepEqual(ids(body["listings"]), []string{"400"}) ||
		body["location"].(map[string]interface{})["label"] != "Ashburn, VA" {
		t.Errorf("group search: %v", body)
	}
	if _, body := get(config, "search", "?s=dentists"); body["category"] != "dentists" {
		t.Errorf("keyword category: category %v", body["category"])
	}
	if _, body := get(config, "search", "?s=alpha&loc=Los+Angeles"); body["category"] != "" || body["location"].(map[string]interface{})["label"] != "Los Angeles, CA" {
		t.Errorf("bare city, no category: %v", body)
	}
	// With a radius the group takes in Sterling's listing, nearest last.
	radius := testClientConfig(t, strings.Replace(testDirectoryConfig, `"pageSize": 2,`, `"pageSize": 2, "radiusMiles": 15,`, 1))
	if _, body := get(radius, "search", "?s=food-and-dining&loc=Ashburn,VA"); !reflect.DeepEqual(ids(body["listings"]), []string{"400", "401"}) ||
		body["location"].(map[string]interface{})["city"] != "Ashburn" {
		t.Errorf("radius group search: %v", body)
	}

	useTestListings(t, listings.Disabled{})
	for _, id := range []string{"states", "cities"} {
		rec, body := get(config, id, "?state=va")
		if rec.Code != http.StatusServiceUnavailable || body["error"] != "listings_unavailable" || rec.Header().Get("Cache-Control") != "no-store" {
			t.Errorf("%s while unavailable: %d %v", id, rec.Code, body)
		}
	}
}

func TestDirectoryStatesAndCategoryPages(t *testing.T) {
	useTestListings(t, testListingsStore(t))
	config := testClientConfig(t, testDirectoryConfig)
	tpl := pageTemplatesFrom("../web/templates")
	other := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	states := directoryStatesHandler(other, tpl)
	category := directoryCategoryHandler(other, tpl)
	slug := func(s string) httprouter.Params { return httprouter.Params{{Key: "slug", Value: s}} }

	for _, tt := range []struct {
		name     string
		handler  http.Handler
		path     string
		params   httprouter.Params
		status   int
		location string
		want     []string
	}{
		{"states", states, "/states", nil, http.StatusOK, "", []string{
			"<title>Browse by state - Local Test</title>", `content="index,follow"`, `href="https://localtest.com/states"`, `"pageName":"listingStates"`,
		}},
		{"states, trailing slash", states, "/states/", nil, http.StatusMovedPermanently, "/states", nil},
		{"category", category, "/categories/food-and-dining", slug("food-and-dining"), http.StatusOK, "", []string{
			"<title>Food &amp; Dining - Local Test</title>", `content="noindex,follow"`, `href="https://localtest.com/categories/food-and-dining"`,
			`"pageName":"listingCategory"`, `"item": "https://localtest.com/categories"`,
		}},
		{"category, query ignored", category, "/categories/food-and-dining?x=1", slug("food-and-dining"), http.StatusOK, "", []string{
			`href="https://localtest.com/categories/food-and-dining"`,
		}},
		{"category without keywords: no subcategories, no page", category, "/categories/dentists", slug("dentists"), http.StatusNotFound, "", nil},
		{"category, other spelling, query dropped", category, "/categories/Food-And-Dining?x=1", slug("Food-And-Dining"), http.StatusMovedPermanently, "/categories/food-and-dining", nil},
		{"category, trailing slash", category, "/categories/food-and-dining/", slug("food-and-dining"), http.StatusMovedPermanently, "/categories/food-and-dining", nil},
		{"unknown category", category, "/categories/hotels", slug("hotels"), http.StatusNotFound, "", nil},
		{"unknown category, trailing slash: no redirect", category, "/categories/hotels/", slug("hotels"), http.StatusNotFound, "", nil},
		{"junk category", category, "/categories/~x~", slug("~x~"), http.StatusNotFound, "", nil},
	} {
		t.Run(tt.name, func(t *testing.T) {
			rec := serveWith(tt.handler, config, tt.path, tt.params)
			if rec.Code != tt.status {
				t.Fatalf("status = %d, want %d", rec.Code, tt.status)
			}
			if rec.Header().Get("Location") != tt.location {
				t.Errorf("Location = %q, want %q", rec.Header().Get("Location"), tt.location)
			}
			if tt.status == http.StatusMovedPermanently && rec.Header().Get("Cache-Control") != seoRedirectCacheControl {
				t.Errorf("redirect Cache-Control = %q", rec.Header().Get("Cache-Control"))
			}
			for _, want := range tt.want {
				if !strings.Contains(rec.Body.String(), want) {
					t.Errorf("page is missing %s", want)
				}
			}
		})
	}

	// Category pages don't need the store.
	useTestListings(t, listings.Disabled{})
	if rec := serveWith(category, config, "/categories/food-and-dining", slug("food-and-dining")); rec.Code != http.StatusOK {
		t.Errorf("category while unavailable: %d, want 200", rec.Code)
	}
	magazine := testClientConfig(t, `{"template": "magazine"}`)
	for _, h := range []http.Handler{states, category} {
		if rec := serveWith(h, magazine, "/states", slug("dentists")); rec.Code != http.StatusTeapot {
			t.Errorf("magazine site: %d, want it routed as before", rec.Code)
		}
	}
}

func TestLegacyURLMiddleware_DirectoryListings(t *testing.T) {
	useTestListings(t, testListingsStore(t))
	config := testClientConfig(t, testDirectoryConfig)
	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := legacyURLMiddleware(next, pageTemplatesFrom("../web/templates"))
	detail := "/va/ashburn/41625316-ashburn-childrens-dentistry-dr-lynda-dean-duru"

	for _, tt := range []struct {
		name     string
		path     string
		status   int
		location string
	}{
		{"old listing URL", "/business/41625316-ashburn-childrens-dentistry", http.StatusMovedPermanently, detail},
		{"old listing URL, slash and query dropped", "/business/41625316-x/?utm_source=a", http.StatusMovedPermanently, detail},
		{"unknown listing", "/business/99999-nope", http.StatusNotFound, ""},
		{"id that isn't digits", "/biz/abc", http.StatusNotFound, ""},
		{"id-only pattern match", "/biz/400", http.StatusMovedPermanently, "/va/ashburn/400-test-pizza-place"},
		{"no slug: not this pattern", "/business/41625316", http.StatusTeapot, ""},
		{"junk under /business", "/business/41625316-x/y", http.StatusTeapot, ""},
		// A legacy search redirect whose query already has s drops the old keyword params, one hop.
		{"s and keyword", "/business/Pizza?keyword=Pizza", http.StatusMovedPermanently, "/search?s=Pizza"},
		{"s and keyword, others kept", "/business/Pizza?keyword=Pizza&loc=Ashburn%2C+VA&q=x", http.StatusMovedPermanently, "/search?s=Pizza&loc=Ashburn%2C+VA"},
	} {
		t.Run(tt.name, func(t *testing.T) {
			rec := serveWith(handler, config, tt.path, nil)
			if rec.Code != tt.status || rec.Header().Get("Location") != tt.location {
				t.Fatalf("%d %q, want %d %q", rec.Code, rec.Header().Get("Location"), tt.status, tt.location)
			}
			if tt.status == http.StatusMovedPermanently && rec.Header().Get("Cache-Control") != seoRedirectCacheControl {
				t.Errorf("redirect Cache-Control = %q", rec.Header().Get("Cache-Control"))
			}
			if tt.status == http.StatusNotFound && rec.Header().Get("X-Robots-Tag") != "noindex, nofollow" {
				t.Errorf("404 X-Robots-Tag = %q", rec.Header().Get("X-Robots-Tag"))
			}
		})
	}

	useTestListings(t, listings.Disabled{})
	rec := serveWith(handler, config, "/business/41625316-x", nil)
	if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "3600" || rec.Header().Get("X-Robots-Tag") != "noindex, nofollow" {
		t.Errorf("unavailable: %d %q %q, want the 503 page", rec.Code, rec.Header().Get("Retry-After"), rec.Header().Get("X-Robots-Tag"))
	}

	// Other sites: the listings patterns don't apply, and keyword is renamed to the article search's term.
	magazine := testClientConfig(t, strings.Replace(testDirectoryConfig, `"template": "directory"`, `"template": "magazine"`, 1))
	if rec := serveWith(handler, magazine, "/business/41625316-x", nil); rec.Code != http.StatusTeapot {
		t.Errorf("magazine site: %d, want routed on", rec.Code)
	}
	if rec := serveWith(handler, magazine, "/business/Pizza?keyword=Pizza", nil); rec.Header().Get("Location") != "/search?s=Pizza&term=Pizza" {
		t.Errorf("magazine site: Location %q", rec.Header().Get("Location"))
	}
}

// TestDirectoryDeletedArticle: on a directory site an article URL the CMS
// doesn't have, whose category isn't the site's, is a 404, not a 301 home.
func TestDirectoryDeletedArticle(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		switch r.URL.Query().Get("action") {
		case "getcategories":
			w.Write([]byte(`{"data":{"localtest.com":[{"cat_id":"1","cat_name":"Articles"}]}}`))
		case "getcategoryarticles":
			w.Write([]byte(`{"data":[]}`))
		default:
			w.Write([]byte(`{"data": false}`))
		}
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()

	handler := notFoundHandler(pageTemplatesFrom("../web/templates"))
	directory := testClientConfig(t, testDirectoryConfig)
	editorial := testClientConfig(t, `{"displayName": "Other", "template": "editorial"}`)
	for _, tt := range []struct {
		config   *middlewares.ClientConfig
		path     string
		status   int
		location string
	}{
		{directory, "/business/41625316", http.StatusNotFound, ""},
		{directory, "/business/41625316-some-name", http.StatusNotFound, ""},
		{directory, "/articles/5677-gone", http.StatusMovedPermanently, "/articles"},
		{editorial, "/business/41625316", http.StatusMovedPermanently, "/"},
	} {
		rec := serveWith(handler, tt.config, tt.path, nil)
		if rec.Code != tt.status || rec.Header().Get("Location") != tt.location {
			t.Errorf("%s: %d %q, want %d %q", tt.path, rec.Code, rec.Header().Get("Location"), tt.status, tt.location)
		}
	}
}

func TestDataPlacesHandler(t *testing.T) {
	orig := placeTextStore
	store, err := places.Load("../internal/places/testdata")
	if err != nil {
		t.Fatal(err)
	}
	placeTextStore = store
	t.Cleanup(func() { placeTextStore = orig })

	handler := DataPlacesHandler()
	full := testClientConfig(t, testDirectoryConfig)
	intro := testClientConfig(t, strings.Replace(testDirectoryConfig, `"state": "full"`, `"state": "intro"`, 1))
	off := testClientConfig(t, strings.Replace(testDirectoryConfig, `"placeText": {"state": "full", "city": "intro"}`, `"placeText": {}`, 1))
	magazine := testClientConfig(t, `{"template": "magazine", "directory": {"placeText": {"state": "full", "city": "intro"}}}`)
	params := func(st, city string) httprouter.Params {
		p := httprouter.Params{{Key: "st", Value: st}}
		if city != "" {
			p = append(p, httprouter.Param{Key: "city", Value: city})
		}
		return p
	}

	for _, tt := range []struct {
		name     string
		config   *middlewares.ClientConfig
		st, city string
		status   int
		want     map[string]interface{}
	}{
		{"state, full", full, "VA", "", http.StatusOK, map[string]interface{}{
			"title": "Virginia", "paragraphs": []interface{}{"Test intro paragraph one.", "Test intro paragraph two."},
			"sections":  []interface{}{map[string]interface{}{"heading": "History", "paragraphs": []interface{}{"Test history paragraph."}}},
			"sourceUrl": "https://en.wikipedia.org/wiki/Virginia", "license": "CC BY-SA 4.0",
		}},
		{"state, intro", intro, "va", "", http.StatusOK, map[string]interface{}{
			"title": "Virginia", "paragraphs": []interface{}{"Test intro paragraph one.", "Test intro paragraph two."},
			"sourceUrl": "https://en.wikipedia.org/wiki/Virginia", "license": "CC BY-SA 4.0",
		}},
		{"city", full, "va", "ashburn", http.StatusOK, map[string]interface{}{
			"title": "Ashburn, Virginia", "paragraphs": []interface{}{"Test city paragraph."},
			"sourceUrl": "https://en.wikipedia.org/wiki/Ashburn,_Virginia", "license": "CC BY-SA 4.0",
		}},
		{"state off", off, "va", "", http.StatusNotFound, map[string]interface{}{"error": "not_found"}},
		{"city off", off, "va", "ashburn", http.StatusNotFound, map[string]interface{}{"error": "not_found"}},
		{"no text", full, "ny", "", http.StatusNotFound, map[string]interface{}{"error": "not_found"}},
		{"unknown city", full, "va", "nowhere-else", http.StatusNotFound, map[string]interface{}{"error": "not_found"}},
		{"junk state", full, "../etc", "", http.StatusNotFound, map[string]interface{}{"error": "not_found"}},
		{"not a directory site", magazine, "va", "", http.StatusNotFound, map[string]interface{}{"error": "not_found"}},
	} {
		rec := serveWith(handler, tt.config, "/data/places/x", params(tt.st, tt.city))
		body := map[string]interface{}{}
		if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
			t.Fatalf("%s: %v", tt.name, err)
		}
		if rec.Code != tt.status || !reflect.DeepEqual(body, tt.want) {
			t.Errorf("%s: %d %v, want %d %v", tt.name, rec.Code, body, tt.status, tt.want)
		}
		wantCache := placesCacheControl
		if tt.status != http.StatusOK {
			wantCache = listingsCacheControl
		}
		if rec.Header().Get("Cache-Control") != wantCache {
			t.Errorf("%s: Cache-Control %q, want %q", tt.name, rec.Header().Get("Cache-Control"), wantCache)
		}
	}
}

func TestOpeningHours(t *testing.T) {
	got := openingHours([]string{
		"Monday : 8:00 AM - 5:00 PM",
		"Tuesday : Closed",
		"Wednesday : 11:00 AM - 3:00 PM , 5:00 PM - 10:00 PM",
		"Thursday : 12:00 AM - 11:59 PM",
		"Friday : 11:00 AM - 4:00 AM",
		"saturday: 9 am - 12 pm",
		"Sunday : Open 24 Hours",
		"Someday : 8:00 AM - 5:00 PM",
		"Monday : 13:00 PM - 5:00 PM",
		"",
		// The listings' variants (fixtures 322498, 42715121).
		"Tuesday : Open All Day",
		"Wednesday :  open all  day ",
		"Thursday : Open All Night",
		"Friday : 10:00 AM - 12:00 AM",
		"Saturday : 5:00 PM - 12:30 AM",
	})
	want := []string{"Mo 08:00-17:00", "We 11:00-15:00", "We 17:00-22:00", "Th 00:00-23:59", "Fr 11:00-04:00", "Sa 09:00-12:00", "Su 00:00-23:59",
		"Tu 00:00-23:59", "We 00:00-23:59", "Fr 10:00-00:00", "Sa 17:00-00:30"}
	if !reflect.DeepEqual(got, want) {
		t.Errorf("openingHours = %q, want %q", got, want)
	}
}

func TestDirectorySitemapPages(t *testing.T) {
	if got := strings.Join(sitemapPagesFromConfig(testClientConfig(t, testDirectoryConfig)), " "); got != "/ /categories /states /sitemap" {
		t.Errorf("directory site: %q", got)
	}
	other := testClientConfig(t, `{"template": "magazine", "sitemapPages": ["/", "/categories", "/states"]}`)
	if got := strings.Join(sitemapPagesFromConfig(other), " "); got != "/ /sitemap" {
		t.Errorf("magazine site: %q", got)
	}
}

func TestShopAffiliateFromConfig(t *testing.T) {
	for configJSON, want := range map[string]string{
		`{"shared": {"shop": {"affiliate": " cured.com "}}, "shop_affiliate": "old"}`: "cured.com",
		`{"shared": {"shop": {}}, "shop_affiliate": "old"}`:                           "old",
		`{}`: "",
	} {
		if got := shopAffiliateFromConfig(testClientConfig(t, configJSON)); got != want {
			t.Errorf("%s: %q, want %q", configJSON, got, want)
		}
	}
	if got := shopAffiliateFromConfig(nil); got != "" {
		t.Errorf("nil config: %q", got)
	}
}
