package routes

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"sync"
	"testing"
	"time"

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

// -----------------------------------------------------------------------------
// URL, host, and slug helpers
// -----------------------------------------------------------------------------

func TestRequestPublicBaseURLUsesForwardedHost(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/sitemap.xml", nil)
	req.Host = "internal:8080"
	req.Header.Set("X-Forwarded-Host", "pointwines.com")
	req.Header.Set("X-Forwarded-Proto", "https")
	if got := requestPublicBaseURL(req); got != "https://pointwines.com" {
		t.Fatalf("base = %q", got)
	}
}

func TestCanonicalURL(t *testing.T) {
	t.Run("homepage", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/", nil)
		req.Host = "bodytheory.com"
		if got := canonicalURL(req); got != "https://bodytheory.com/" {
			t.Fatalf("got %q", got)
		}
	})

	t.Run("static page", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/about", nil)
		req.Host = "bodytheory.com"
		if got := canonicalURL(req); got != "https://bodytheory.com/about" {
			t.Fatalf("got %q", got)
		}
	})

	t.Run("article path", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/fitness/1775223-functional-training-for-total-body-strength-results-guide", nil)
		req.Host = "uat-bodytheory.imds.tv"
		want := "https://uat-bodytheory.imds.tv/fitness/1775223-functional-training-for-total-body-strength-results-guide"
		if got := canonicalURL(req); got != want {
			t.Fatalf("got %q", got)
		}
	})

	t.Run("strips search term", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/search?term=skin&utm_source=x", nil)
		req.Host = "bodytheory.com"
		if got := canonicalURL(req); got != "https://bodytheory.com/search" {
			t.Fatalf("got %q", got)
		}
	})

	t.Run("keeps page greater than 1", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/fitness?page=2", nil)
		req.Host = "bodytheory.com"
		if got := canonicalURL(req); got != "https://bodytheory.com/fitness?page=2" {
			t.Fatalf("got %q", got)
		}
	})

	t.Run("omits page=1", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/fitness?page=1", nil)
		req.Host = "bodytheory.com"
		if got := canonicalURL(req); got != "https://bodytheory.com/fitness" {
			t.Fatalf("got %q", got)
		}
	})

	t.Run("forwarded host and proto", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/privacy", nil)
		req.Host = "127.0.0.1:8080"
		req.Header.Set("X-Forwarded-Host", "pointwines.com")
		req.Header.Set("X-Forwarded-Proto", "https")
		if got := canonicalURL(req); got != "https://pointwines.com/privacy" {
			t.Fatalf("got %q", got)
		}
	})
}

func TestSlugify(t *testing.T) {
	cases := map[string]string{
		"Fitness":     "fitness",
		"Wine Tips":   "wine-tips",
		"  Health  ":  "health",
		"Total Body!": "total-body",
		"A--B":        "a-b",
		// Parity with oos-singlecube's JS slugify (outputs taken from it).
		"Rosé & More":      "ros-and-more",
		"Wine\u00a0Tips":   "wine-tips",
		"Tab\tSep":         "tab-sep",
		"snake_case_title": "snake-case-title",
		"Café—Crème 2026":  "cafcrme-2026",
		// "&" is spelled out as "and", like the legacy sites' category URLs.
		"Claims & Coverage": "claims-and-coverage",
		"Claim & Coverage":  "claim-and-coverage",
		"Cost & Coverage":   "cost-and-coverage",
		"A&B":               "a-and-b",
		"R&D":               "r-and-d",
		"A & & B":           "a-and-and-b",
		"& Leading":         "and-leading",
		"Trailing &":        "trailing-and",
		"&":                 "and",
		// Category names from the other theme2 sites
		"Risk & Planning":       "risk-and-planning",
		"Flowers & Ornamentals": "flowers-and-ornamentals",
		"Tips&Hacks":            "tips-and-hacks",
	}
	for in, want := range cases {
		if got := slugify(in); got != want {
			t.Errorf("slugify(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestSlugifyArticleTitle(t *testing.T) {
	// Same cases as oos-singlecube's slugifyArticleTitle test: "&" is dropped,
	// so article slugs match the legacy sites' sitemaps and stay unchanged.
	cases := map[string]string{
		"Insurance Claim Process Timeline & Steps": "insurance-claim-process-timeline-steps",
		"Claims & Coverage":                        "claims-coverage",
		"A&B":                                      "ab",
		"A & & B":                                  "a-b",
		"& Leading":                                "leading",
		"Trailing &":                               "trailing",
		"&":                                        "",
		"Food And Wine":                            "food-and-wine",
	}
	for in, want := range cases {
		if got := slugifyArticleTitle(in); got != want {
			t.Errorf("slugifyArticleTitle(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestHumanizeSlug(t *testing.T) {
	cases := map[string]string{
		"wine-tips": "Wine Tips",
		"fitness":   "Fitness",
		"":          "",
	}
	for in, want := range cases {
		if got := humanizeSlug(in); got != want {
			t.Errorf("humanizeSlug(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestExtractArticleIDFromSlug(t *testing.T) {
	tests := []struct {
		slug string
		want string
	}{
		{"1778500-wine-faults", "1778500"},
		{"1774289", "1774289"},
		{"", ""},
	}

	for _, tt := range tests {
		got := extractArticleIDFromSlug(tt.slug)
		if got != tt.want {
			t.Errorf("extractArticleIDFromSlug(%q) = %q, want %q", tt.slug, got, tt.want)
		}
	}
}

func TestParseArticleDetailPath(t *testing.T) {
	tests := []struct {
		path         string
		wantCategory string
		wantSlug     string
		wantOK       bool
	}{
		{"/wine-tips/1778500-wine-faults", "wine-tips", "1778500-wine-faults", true},
		// /article/:slug is a registered router route so it never reaches parseArticleDetailPath,
		// but the function itself matches it (first segment "article", second starts with digit).
		{"/article/1774289", "article", "1774289", true},
		{"/terms", "", "", false},
		{"/health-check/probe", "", "", false},
		{"/wine-tips/not-an-id", "", "", false},
	}

	for _, tt := range tests {
		category, slug, ok := parseArticleDetailPath(tt.path)
		if ok != tt.wantOK || category != tt.wantCategory || slug != tt.wantSlug {
			t.Errorf("parseArticleDetailPath(%q) = (%q, %q, %v), want (%q, %q, %v)",
				tt.path, category, slug, ok, tt.wantCategory, tt.wantSlug, tt.wantOK)
		}
	}
}

func TestParseSubcategoryArticleDetailPath(t *testing.T) {
	tests := []struct {
		path            string
		wantCategory    string
		wantSubcategory string
		wantSlug        string
		wantOK          bool
	}{
		{"/wine-101/wine-regions/1090-food-and-wine", "wine-101", "wine-regions", "1090-food-and-wine", true},
		{"/wine-101/wine-regions/1090", "wine-101", "wine-regions", "1090", true},
		{"/wine-tips/1778500-wine-faults", "", "", "", false},
		{"/wine-101/wine-regions", "", "", "", false},
		{"/wine-101/wine-regions/not-an-id", "", "", "", false},
		{"/terms", "", "", "", false},
	}

	for _, tt := range tests {
		category, subcategory, slug, ok := parseSubcategoryArticleDetailPath(tt.path)
		if ok != tt.wantOK || category != tt.wantCategory || subcategory != tt.wantSubcategory || slug != tt.wantSlug {
			t.Errorf("parseSubcategoryArticleDetailPath(%q) = (%q, %q, %q, %v), want (%q, %q, %q, %v)",
				tt.path, category, subcategory, slug, ok, tt.wantCategory, tt.wantSubcategory, tt.wantSlug, tt.wantOK)
		}
	}
}

func TestParseCategoryPath(t *testing.T) {
	tests := []struct {
		path     string
		wantSlug string
		wantOK   bool
	}{
		{"/wine", "wine", true},
		{"/spirits", "spirits", true},
		{"/red-wine-tips", "red-wine-tips", true},
		// "health" is a valid category slug (e.g. bodytheory) now that the
		// health-check endpoint lives at /health-check instead of /health.
		{"/health", "health", true},
		// reserved single-segment paths must not match
		{"/terms", "", false},
		{"/sitemap", "", false},
		{"/about", "", false},
		{"/search", "", false},
		{"/articles", "", false},
		{"/health-check", "", false},
		// only plain slug segments match
		{"/~", "", false},
		{"/Fitness", "", false},
		{"/evil.com", "", false},
		{"/\\evil.test", "", false},
		{"/fitness/", "fitness", true},
		// multi-segment paths must not match
		{"/health-check/probe", "", false},
		{"/articles/category/101", "", false},
		{"/wine-tips/1778500-wine-faults", "", false},
	}

	for _, tt := range tests {
		slug, ok := parseCategoryPath(tt.path)
		if ok != tt.wantOK || slug != tt.wantSlug {
			t.Errorf("parseCategoryPath(%q) = (%q, %v), want (%q, %v)",
				tt.path, slug, ok, tt.wantSlug, tt.wantOK)
		}
	}
}

// -----------------------------------------------------------------------------
// Canonical article path building + redirect decisions
// -----------------------------------------------------------------------------

func TestBuildArticleDetailPath(t *testing.T) {
	tests := []struct {
		name       string
		category   string
		subCat     string
		articleID  string
		titleSlug  string
		wantResult string
	}{
		{"with subcategory and title", "Wine 101", "Wine Regions", "26165", "The Top Pinot Noir Regions To Visit For Wine Lovers", "/wine-101/wine-regions/26165-the-top-pinot-noir-regions-to-visit-for-wine-lovers"},
		{"category only, no subcategory", "Fitness", "", "1775223", "Functional Training", "/fitness/1775223-functional-training"},
		{"no title falls back to bare id", "Fitness", "", "1775223", "", "/fitness/1775223"},
		{"no category falls back to /article", "", "", "42", "Some Title", "/article/42-some-title"},
		// "&" reads "and" in category segments but is dropped from the title slug.
		{"ampersand in category and title", "Claims & Coverage", "", "1768953", "Insurance Claim Process Timeline & Steps", "/claims-and-coverage/1768953-insurance-claim-process-timeline-steps"},
		{"ampersand in subcategory", "Blog", "AI SEO & Automation", "7", "Tips & Tricks", "/blog/ai-seo-and-automation/7-tips-tricks"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got := buildArticleDetailPath(tt.category, tt.subCat, tt.articleID, tt.titleSlug)
			if got != tt.wantResult {
				t.Errorf("buildArticleDetailPath(%q, %q, %q, %q) = %q, want %q",
					tt.category, tt.subCat, tt.articleID, tt.titleSlug, got, tt.wantResult)
			}
		})
	}
}

func TestArticleCanonicalRedirectPath(t *testing.T) {
	t.Run("redirects when subcategory is missing from the URL", func(t *testing.T) {
		meta := articlePageMeta{Category: "Wine 101", SubCategory: "Wine Regions", SlugTitle: "food and wine"}
		got := articleCanonicalRedirectPath(meta, "1090", "/wine-101/1090-food-and-wine")
		want := "/wine-101/wine-regions/1090-food-and-wine"
		if got != want {
			t.Fatalf("got %q, want %q", got, want)
		}
	})

	t.Run("redirects when the slug is just the bare article id", func(t *testing.T) {
		meta := articlePageMeta{Category: "Wine 101", SubCategory: "Wine Regions", SlugTitle: "The Top Pinot Noir Regions To Visit For Wine Lovers"}
		got := articleCanonicalRedirectPath(meta, "26165", "/wine-101/wine-regions/26165")
		want := "/wine-101/wine-regions/26165-the-top-pinot-noir-regions-to-visit-for-wine-lovers"
		if got != want {
			t.Fatalf("got %q, want %q", got, want)
		}
	})

	t.Run("redirects when both subcategory and title slug are missing", func(t *testing.T) {
		meta := articlePageMeta{Category: "Wine 101", SubCategory: "Wine Regions", SlugTitle: "Food And Wine"}
		got := articleCanonicalRedirectPath(meta, "1090", "/article/1090")
		want := "/wine-101/wine-regions/1090-food-and-wine"
		if got != want {
			t.Fatalf("got %q, want %q", got, want)
		}
	})

	t.Run("no redirect when already canonical", func(t *testing.T) {
		meta := articlePageMeta{Category: "Wine 101", SubCategory: "Wine Regions", SlugTitle: "Food And Wine"}
		got := articleCanonicalRedirectPath(meta, "1090", "/wine-101/wine-regions/1090-food-and-wine")
		if got != "" {
			t.Fatalf("got %q, want no redirect", got)
		}
	})

	t.Run("no redirect when there is no subcategory and no title to add", func(t *testing.T) {
		meta := articlePageMeta{Category: "Fitness"}
		got := articleCanonicalRedirectPath(meta, "1775223", "/fitness/1775223")
		if got != "" {
			t.Fatalf("got %q, want no redirect", got)
		}
	})

	t.Run("redirects a trailing slash to the clean path", func(t *testing.T) {
		meta := articlePageMeta{Category: "Weight Loss Tips", SlugTitle: "Calorie Deficit Guide for Safer Healthier Weight Loss"}
		got := articleCanonicalRedirectPath(meta, "1780517", "/weight-loss-tips/1780517-calorie-deficit-guide-for-safer-healthier-weight-loss/")
		want := "/weight-loss-tips/1780517-calorie-deficit-guide-for-safer-healthier-weight-loss"
		if got != want {
			t.Fatalf("got %q, want %q", got, want)
		}
	})

	t.Run("redirects legacy /articles/ URLs with an outdated slug", func(t *testing.T) {
		meta := articlePageMeta{Category: "Weight Loss Tips", SlugTitle: "Calorie Deficit Guide for Safer Healthier Weight Loss"}
		got := articleCanonicalRedirectPath(meta, "1780517", "/articles/1780517-calorie-deficit-guide-for-safer-and-healthier-weight-loss/")
		want := "/weight-loss-tips/1780517-calorie-deficit-guide-for-safer-healthier-weight-loss"
		if got != want {
			t.Fatalf("got %q, want %q", got, want)
		}
	})

	t.Run("redirects an old category segment to the current category", func(t *testing.T) {
		meta := articlePageMeta{Category: "Weight Loss Tips", SlugTitle: "Easy Homemade Weight Loss Drinks for a Healthier You"}
		got := articleCanonicalRedirectPath(meta, "1760498", "/weight-loss/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you")
		want := "/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you"
		if got != want {
			t.Fatalf("got %q, want %q", got, want)
		}
	})

	t.Run("no redirect for a non-numeric article id", func(t *testing.T) {
		meta := articlePageMeta{Category: "Fitness", SlugTitle: "Functional Training"}
		got := articleCanonicalRedirectPath(meta, `1775223\evil`, `/fitness/1775223\evil-x/`)
		if got != "" {
			t.Fatalf("got %q, want no redirect", got)
		}
	})

	t.Run("no redirect without a CMS category", func(t *testing.T) {
		meta := articlePageMeta{SlugTitle: "Functional Training"}
		got := articleCanonicalRedirectPath(meta, "1775223", "/fitness/1775223-something-else")
		if got != "" {
			t.Fatalf("got %q, want no redirect", got)
		}
	})

	t.Run("does not loop when the title slugifies to empty", func(t *testing.T) {
		meta := articlePageMeta{Category: "Fitness", SlugTitle: "!!!"}
		got := articleCanonicalRedirectPath(meta, "1775223", "/fitness/1775223")
		if got != "" {
			t.Fatalf("got %q, want no redirect (target would equal current path)", got)
		}
	})
}

func TestTrailingSlashRedirectPath(t *testing.T) {
	tests := []struct {
		path   string
		want   string
		wantOK bool
	}{
		{"/", "", false},
		{"/fitness", "", false},
		{"/fitness/", "/fitness", true},
		{"/wine-101/wine-types/", "/wine-101/wine-types", true},
		{"/dieting-tips//", "/dieting-tips", true},
		// Never an off-site target: only plain slug segments redirect.
		{"//evil.com/", "", false},
		{"///", "", false},
		{"//a//b/", "", false},
		{`/\evil.com/`, "", false},
		{`/\\evil.com/`, "", false},
		{`/\/evil.com/`, "", false},
		{"/\t/evil.test/", "", false},
		{"/Fitness/", "", false},
		// Deeper or reserved paths aren't listing pages: no redirect, plain 404.
		{"/a/b/c/d/", "", false},
		{"/fitness/1775223-functional-training/", "", false},
		{"/search/", "", false},
		// Static pages aren't listing pages either: the router redirects
		// /about/ itself (see TestRedirectCacheControlMiddleware).
		{"/about/", "", false},
		{"/contactus/", "", false},
	}
	for _, tt := range tests {
		got, ok := trailingSlashRedirectPath(tt.path)
		if got != tt.want || ok != tt.wantOK {
			t.Errorf("trailingSlashRedirectPath(%q) = (%q, %v), want (%q, %v)", tt.path, got, ok, tt.want, tt.wantOK)
		}
	}
}

// The router's own 301s get the SEO redirect cache lifetime; other statuses
// and a Cache-Control a handler already set are left alone.
func TestRedirectCacheControlMiddleware(t *testing.T) {
	router := httprouter.New()
	ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
	router.Handler(http.MethodGet, "/about", ok)
	router.Handler(http.MethodPost, "/data/contact", ok)
	router.Handler(http.MethodGet, "/old", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-store")
		http.Redirect(w, r, "/new", http.StatusMovedPermanently)
	}))
	handler := RedirectCacheControlMiddleware(router)

	tests := []struct {
		method, path  string
		wantCode      int
		wantLocation  string
		wantCacheCtrl string
	}{
		{http.MethodGet, "/about/?x=1", http.StatusMovedPermanently, "/about?x=1", "public, max-age=3600"},
		{http.MethodGet, "/About", http.StatusMovedPermanently, "/about", "public, max-age=3600"},
		{http.MethodPost, "/data/contact/", http.StatusTemporaryRedirect, "/data/contact", ""},
		{http.MethodGet, "/old", http.StatusMovedPermanently, "/new", "no-store"},
		{http.MethodGet, "/about", http.StatusOK, "", ""},
	}
	for _, tt := range tests {
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, httptest.NewRequest(tt.method, tt.path, nil))
		if rec.Code != tt.wantCode || rec.Header().Get("Location") != tt.wantLocation || rec.Header().Get("Cache-Control") != tt.wantCacheCtrl {
			t.Errorf("%s %s = %d, Location %q, Cache-Control %q; want %d, %q, %q", tt.method, tt.path,
				rec.Code, rec.Header().Get("Location"), rec.Header().Get("Cache-Control"), tt.wantCode, tt.wantLocation, tt.wantCacheCtrl)
		}
	}

	// The wrapper doesn't hide the underlying writer from http.ResponseController.
	rec := httptest.NewRecorder()
	if err := http.NewResponseController(redirectCacheControlWriter{rec}).Flush(); err != nil || !rec.Flushed {
		t.Errorf("Flush through the wrapper: err %v, flushed %v", err, rec.Flushed)
	}
}

// -----------------------------------------------------------------------------
// Per-page meta title/description overrides
// -----------------------------------------------------------------------------

func TestPageMetaOverride(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"seoMeta": {
			"home": {
				"title": "BodyTheory: Health, Fitness & Wellness Tips for Better Living",
				"description": "Discover expert-backed health, fitness, and wellness advice."
			},
			"health": {
				"title": "Health Tips, Nutrition & Healthy Living Guides | BodyTheory"
			}
		}
	}`, httptest.NewRequest("GET", "/", nil))
	config := middlewares.GetClientConfig(req.Context())

	t.Run("full override", func(t *testing.T) {
		title, desc := pageMetaOverride(config, "home", "fallback title", "fallback description")
		if title != "BodyTheory: Health, Fitness & Wellness Tips for Better Living" {
			t.Fatalf("title = %q", title)
		}
		if desc != "Discover expert-backed health, fitness, and wellness advice." {
			t.Fatalf("description = %q", desc)
		}
	})

	t.Run("partial override falls back for the missing field", func(t *testing.T) {
		title, desc := pageMetaOverride(config, "health", "fallback title", "fallback description")
		if title != "Health Tips, Nutrition & Healthy Living Guides | BodyTheory" {
			t.Fatalf("title = %q", title)
		}
		if desc != "fallback description" {
			t.Fatalf("description = %q, want fallback", desc)
		}
	})

	t.Run("no override falls back entirely", func(t *testing.T) {
		title, desc := pageMetaOverride(config, "fitness", "fallback title", "fallback description")
		if title != "fallback title" || desc != "fallback description" {
			t.Fatalf("title = %q, description = %q", title, desc)
		}
	})

	t.Run("nil config and empty key are safe", func(t *testing.T) {
		title, desc := pageMetaOverride(nil, "home", "fallback title", "fallback description")
		if title != "fallback title" || desc != "fallback description" {
			t.Fatalf("nil config: title = %q, description = %q", title, desc)
		}
		title, desc = pageMetaOverride(config, "", "fallback title", "fallback description")
		if title != "fallback title" || desc != "fallback description" {
			t.Fatalf("empty key: title = %q, description = %q", title, desc)
		}
	})
}

// TestBodytheorySeoMetaConfig loads the real client_configs/bodytheory.json
// from disk to guard against typos/structural mistakes in seoMeta that a
// hand-authored test fixture wouldn't catch.
func TestBodytheorySeoMetaConfig(t *testing.T) {
	raw, err := os.ReadFile("../client_configs/bodytheory.json")
	if err != nil {
		t.Fatalf("reading bodytheory.json: %v", err)
	}
	req := middlewares.GetReqWithClientConfig(string(raw), httptest.NewRequest("GET", "/", nil))
	config := middlewares.GetClientConfig(req.Context())

	cases := []struct {
		key             string
		wantTitle       string
		wantDescription string
	}{
		{"home", "Wellness, Health & Fitness Tips and Guides | BodyTheory.com", "Explore wellness, health, and fitness guidance with practical tips and helpful information to support healthy habits, physical activity & everyday well-being."},
		{"health", "Health Tips, Prevention & Healthy Living | BodyTheory.com", "Find accessible health information and practical tips on prevention, everyday health habits, and well-being to help you make informed lifestyle choices."},
		{"fitness", "Fitness Tips, Workouts & Exercise Guides | BodyTheory.com", "Explore fitness tips, workout ideas, and exercise guidance for different experience levels to build strength, improve endurance & maintain an active lifestyle."},
		{"wellness", "Wellness Tips, Self-Care & Healthy Living | BodyTheory.com", "Discover wellness tips, self-care ideas, and healthy lifestyle habits to support everyday well-being, manage daily routines, and build a more balanced life."},
		{"contactUs", "Contact Us | BodyTheory", "Have questions or feedback? Contact BodyTheory for assistance, content inquiries, partnership opportunities, or general support."},
		{"aboutUs", "About Us | BodyTheory", "Learn about BodyTheory's mission to provide reliable health, fitness, and wellness content that helps readers live healthier lives."},
		{"privacyPolicy", "Privacy Policy | BodyTheory", "Review BodyTheory's Privacy Policy to learn how we collect, use, store, and protect your personal information and browsing data."},
		{"terms", "Terms & Conditions | BodyTheory", "Read the Terms & Conditions for using BodyTheory, including user responsibilities, content usage guidelines, and legal information."},
		{"sitemap", "Sitemap - Explore All BodyTheory Articles & Resources | BodyTheory", "Browse the BodyTheory sitemap to quickly access health articles, fitness guides, wellness resources, and important website pages."},
		{"search", "Search Results | BodyTheory", "Browse search results and discover health, fitness, and wellness content available on BodyTheory."},
	}

	for _, tc := range cases {
		title, desc := pageMetaOverride(config, tc.key, "MISSING TITLE", "MISSING DESCRIPTION")
		if title != tc.wantTitle {
			t.Errorf("%s: title = %q, want %q", tc.key, title, tc.wantTitle)
		}
		if desc != tc.wantDescription {
			t.Errorf("%s: description = %q, want %q", tc.key, desc, tc.wantDescription)
		}
	}
}

// -----------------------------------------------------------------------------
// Config-derived SEO metadata
// -----------------------------------------------------------------------------

func TestFaviconURLFromConfig_explicit(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "pointwines",
		"favicon_url": "https://portal-static.imds-cdn.com/oos/pointwines/favicon.png"
	}`, httptest.NewRequest("GET", "/", nil))

	got := faviconURLFromConfig(middlewares.GetClientConfig(req.Context()))
	want := "https://portal-static.imds-cdn.com/oos/pointwines/favicon.png"
	if got != want {
		t.Fatalf("got %q, want %q", got, want)
	}
}

func TestFaviconURLFromConfig_derived(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "pointwines",
		"portal_static_cdn_url": "https://portal-static.imds-cdn.com"
	}`, httptest.NewRequest("GET", "/", nil))

	got := faviconURLFromConfig(middlewares.GetClientConfig(req.Context()))
	want := "https://portal-static.imds-cdn.com/oos/pointwines/favicon.png"
	if got != want {
		t.Fatalf("got %q, want %q", got, want)
	}
}

func TestFaviconURLFromConfig_missing(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{"siteId": "pointwines"}`, httptest.NewRequest("GET", "/", nil))
	if got := faviconURLFromConfig(middlewares.GetClientConfig(req.Context())); got != "" {
		t.Fatalf("got %q, want empty", got)
	}
}

func TestGoogleSiteVerificationFromConfig(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"google_site_verification": "hwXRZRS3qHnDfZzz2K3tBoGhSK5uq2xmSAkd5drFpVg"
	}`, httptest.NewRequest("GET", "/", nil))

	got := googleSiteVerificationFromConfig(middlewares.GetClientConfig(req.Context()))
	want := "hwXRZRS3qHnDfZzz2K3tBoGhSK5uq2xmSAkd5drFpVg"
	if got != want {
		t.Fatalf("got %q, want %q", got, want)
	}

	emptyReq := middlewares.GetReqWithClientConfig(`{"siteId": "pointwines"}`, httptest.NewRequest("GET", "/", nil))
	if got := googleSiteVerificationFromConfig(middlewares.GetClientConfig(emptyReq.Context())); got != "" {
		t.Fatalf("got %q, want empty", got)
	}
}

// -----------------------------------------------------------------------------
// Meta robots / X-Robots-Tag policy
// -----------------------------------------------------------------------------

func TestApplyMetaRobots_UATAllNoIndex(t *testing.T) {
	viper.Set("environment", "uat")
	t.Cleanup(func() { viper.Set("environment", "") })

	req := httptest.NewRequest("GET", "/about", nil)
	req.Host = "uat-bodytheory.imds.tv"

	for _, kind := range []metaRobotsKind{metaRobotsIndexable, metaRobotsSearch, metaRobotsArticle} {
		vars := &templateVars{MetaRobots: "index,follow"}
		rr := httptest.NewRecorder()
		applyMetaRobots(rr, vars, req, kind)
		if vars.MetaRobots != robotsNoIndexNoFollow {
			t.Fatalf("kind %s: got %q, want %q", kind, vars.MetaRobots, robotsNoIndexNoFollow)
		}
		if got := rr.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" {
			t.Fatalf("kind %s: X-Robots-Tag = %q", kind, got)
		}
	}
}

func TestApplyMetaRobots_ProdPolicies(t *testing.T) {
	viper.Set("environment", "prod")
	t.Cleanup(func() { viper.Set("environment", "") })

	req := httptest.NewRequest("GET", "/", nil)
	req.Host = "bodytheory.com"

	t.Run("indexable", func(t *testing.T) {
		vars := &templateVars{}
		rr := httptest.NewRecorder()
		applyMetaRobots(rr, vars, req, metaRobotsIndexable)
		if vars.MetaRobots != robotsIndexFollow {
			t.Fatalf("got %q", vars.MetaRobots)
		}
		if got := rr.Header().Get("X-Robots-Tag"); got != "index, follow" {
			t.Fatalf("X-Robots-Tag = %q", got)
		}
	})

	t.Run("search", func(t *testing.T) {
		vars := &templateVars{}
		rr := httptest.NewRecorder()
		applyMetaRobots(rr, vars, req, metaRobotsSearch)
		if vars.MetaRobots != robotsNoIndexFollow {
			t.Fatalf("got %q", vars.MetaRobots)
		}
		if got := rr.Header().Get("X-Robots-Tag"); got != "noindex, follow" {
			t.Fatalf("X-Robots-Tag = %q", got)
		}
	})

	t.Run("article indexable", func(t *testing.T) {
		vars := &templateVars{MetaRobots: "index,follow"}
		rr := httptest.NewRecorder()
		applyMetaRobots(rr, vars, req, metaRobotsArticle)
		if vars.MetaRobots != robotsIndexFollow {
			t.Fatalf("got %q", vars.MetaRobots)
		}
		if got := rr.Header().Get("X-Robots-Tag"); got != "index, follow" {
			t.Fatalf("X-Robots-Tag = %q", got)
		}
	})

	t.Run("article cms noindex", func(t *testing.T) {
		vars := &templateVars{MetaRobots: "noindex,nofollow"}
		rr := httptest.NewRecorder()
		applyMetaRobots(rr, vars, req, metaRobotsArticle)
		if vars.MetaRobots != robotsNoIndexNoFollow {
			t.Fatalf("got %q", vars.MetaRobots)
		}
		if got := rr.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" {
			t.Fatalf("X-Robots-Tag = %q", got)
		}
	})
}

func TestApplyMetaRobots_DevEnvironment(t *testing.T) {
	viper.Set("environment", "dev")
	t.Cleanup(func() { viper.Set("environment", "") })

	req := httptest.NewRequest("GET", "/", nil)
	req.Host = "bodytheory.com" // even with prod-like host, non-prod env wins
	vars := &templateVars{}
	rr := httptest.NewRecorder()
	applyMetaRobots(rr, vars, req, metaRobotsIndexable)
	if vars.MetaRobots != robotsNoIndexNoFollow {
		t.Fatalf("got %q", vars.MetaRobots)
	}
	if got := rr.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" {
		t.Fatalf("X-Robots-Tag = %q", got)
	}
}

func TestNonProdXRobotsTagMiddleware(t *testing.T) {
	viper.Set("environment", "uat")
	t.Cleanup(func() { viper.Set("environment", "") })

	inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	})
	handler := NonProdXRobotsTagMiddleware(inner)

	req := httptest.NewRequest("GET", "/data/categories", nil)
	req.Host = "uat-bodytheory.imds.tv"
	rr := httptest.NewRecorder()
	handler.ServeHTTP(rr, req)

	if got := rr.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" {
		t.Fatalf("X-Robots-Tag = %q", got)
	}
}

func TestNonProdXRobotsTagMiddleware_SkipsProd(t *testing.T) {
	viper.Set("environment", "prod")
	t.Cleanup(func() { viper.Set("environment", "") })

	inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	handler := NonProdXRobotsTagMiddleware(inner)

	req := httptest.NewRequest("GET", "/", nil)
	req.Host = "bodytheory.com"
	rr := httptest.NewRecorder()
	handler.ServeHTTP(rr, req)

	if got := rr.Header().Get("X-Robots-Tag"); got != "" {
		t.Fatalf("prod middleware should not set X-Robots-Tag, got %q", got)
	}
}

// -----------------------------------------------------------------------------
// CMS → article SEO/social meta parsing
// -----------------------------------------------------------------------------

func TestArticlePageMetaFromCMS_full(t *testing.T) {
	raw := []byte(`{
		"data": {
			"id": "1775223",
			"title": "Functional Training for Total Body Strength Results Guide",
			"meta_title": "Functional Training for Total Body Strength Results Guide",
			"sub_head": "Start functional training today to boost strength gains.  Read more ",
			"keywords": "",
			"category": "Fitness",
			"sub_category": null,
			"author": "Kirandeep kaur",
			"author_name": "Kirandeep Kaur",
			"image": "https://prod-cms-image-contents.s3-us-west-1.amazonaws.com/2026/fit-1771327370-r.jpg",
			"images_attr": "{\"img\":{\"alt\":\"functional training\"}}",
			"slug_title": "functional training",
			"is_index": 1,
			"timestamp": 1771327370
		}
	}`)

	got := articlePageMetaFromCMS(raw)

	if got.Title != "Functional Training for Total Body Strength Results Guide" {
		t.Fatalf("Title = %q", got.Title)
	}
	if got.Description != "Start functional training today to boost strength gains." {
		t.Fatalf("Description = %q", got.Description)
	}
	if got.Keywords != "Fitness" {
		t.Fatalf("Keywords = %q", got.Keywords)
	}
	if got.Author != "Kirandeep Kaur" {
		t.Fatalf("Author = %q", got.Author)
	}
	if got.Robots != "index,follow" {
		t.Fatalf("Robots = %q", got.Robots)
	}
	if got.Image == "" {
		t.Fatal("expected Image")
	}
	if got.ImageAlt != "functional training" {
		t.Fatalf("ImageAlt = %q", got.ImageAlt)
	}
	if got.Category != "Fitness" {
		t.Fatalf("Category = %q", got.Category)
	}

	wantTime := time.Unix(1771327370, 0).UTC().Format(time.RFC3339)
	if got.PublishedTime != wantTime {
		t.Fatalf("PublishedTime = %q, want %q", got.PublishedTime, wantTime)
	}
}

func TestArticlePageMetaFromCMS_noindex(t *testing.T) {
	raw := []byte(`{"data": {"title": "T", "is_index": 0}}`)
	got := articlePageMetaFromCMS(raw)
	if got.Robots != "noindex,nofollow" {
		t.Fatalf("Robots = %q", got.Robots)
	}
}

func TestArticlePageMetaFromCMS_SlugTitleFallbackChain(t *testing.T) {
	t.Run("prefers slug_title", func(t *testing.T) {
		raw := []byte(`{"data": {"slug_title": "slug wins", "meta_title": "meta title", "title": "plain title"}}`)
		if got := articlePageMetaFromCMS(raw).SlugTitle; got != "slug wins" {
			t.Fatalf("SlugTitle = %q, want %q", got, "slug wins")
		}
	})

	t.Run("falls back to meta_title when slug_title is missing", func(t *testing.T) {
		raw := []byte(`{"data": {"meta_title": "meta title", "title": "plain title"}}`)
		if got := articlePageMetaFromCMS(raw).SlugTitle; got != "meta title" {
			t.Fatalf("SlugTitle = %q, want %q", got, "meta title")
		}
	})

	t.Run("falls back to plain title when slug_title and meta_title are missing", func(t *testing.T) {
		raw := []byte(`{"data": {"title": "plain title"}}`)
		if got := articlePageMetaFromCMS(raw).SlugTitle; got != "plain title" {
			t.Fatalf("SlugTitle = %q, want %q", got, "plain title")
		}
	})

	t.Run("empty when none are set", func(t *testing.T) {
		raw := []byte(`{"data": {}}`)
		if got := articlePageMetaFromCMS(raw).SlugTitle; got != "" {
			t.Fatalf("SlugTitle = %q, want empty", got)
		}
	})
}

func TestArticlePageMeta_applyTo(t *testing.T) {
	vars := &templateVars{}
	meta := articlePageMeta{
		Title:         "Article Title",
		Description:   "Article desc",
		Keywords:      "fitness",
		Author:        "Author Name",
		Robots:        "index, follow",
		Image:         "https://example.com/img.jpg",
		ImageAlt:      "alt text",
		Category:      "Fitness",
		PublishedTime: "2026-01-01T00:00:00Z",
	}
	meta.applyTo(vars, "BodyTheory")

	if vars.OgType != "article" {
		t.Fatalf("OgType = %q", vars.OgType)
	}
	if vars.TwitterCard != "summary_large_image" {
		t.Fatalf("TwitterCard = %q", vars.TwitterCard)
	}
	if vars.PageTitle != "Article Title - BodyTheory" {
		t.Fatalf("PageTitle = %q", vars.PageTitle)
	}
	if vars.OgImageWidth != articleOgImageWidth || vars.OgImageHeight != articleOgImageHeight || vars.OgImageType != articleOgImageType {
		t.Fatalf("OgImage dimensions = %q x %q (%q), want %q x %q (%q)",
			vars.OgImageWidth, vars.OgImageHeight, vars.OgImageType,
			articleOgImageWidth, articleOgImageHeight, articleOgImageType)
	}
}

func TestArticlePageMeta_applyTo_noImage(t *testing.T) {
	vars := &templateVars{}
	meta := articlePageMeta{Title: "No Image Article"}
	meta.applyTo(vars, "BodyTheory")

	if vars.OgImageWidth != "" || vars.OgImageHeight != "" || vars.OgImageType != "" {
		t.Fatalf("expected no image dimensions without an image, got %q x %q (%q)", vars.OgImageWidth, vars.OgImageHeight, vars.OgImageType)
	}
	if vars.TwitterCard != "" {
		t.Fatalf("expected no TwitterCard without an image, got %q", vars.TwitterCard)
	}
}

func TestArticlePageMeta_applyTo_noTitleSuffix(t *testing.T) {
	vars := &templateVars{}
	articlePageMeta{Title: "Claim Adjuster"}.applyTo(vars, "")

	if vars.PageTitle != "Claim Adjuster" {
		t.Fatalf("PageTitle = %q, want the bare article title", vars.PageTitle)
	}
	if vars.OgTitle != "Claim Adjuster" || vars.TwitterTitle != "Claim Adjuster" {
		t.Fatalf("OgTitle = %q, TwitterTitle = %q", vars.OgTitle, vars.TwitterTitle)
	}
}

func TestArticleTitleSuffixFromConfig(t *testing.T) {
	tests := []struct {
		name   string
		config string
		want   bool
	}{
		{"unset defaults to true", `{"displayName": "BodyTheory"}`, true},
		{"explicit true", `{"articleTitleSuffix": true}`, true},
		{"explicit false", `{"articleTitleSuffix": false}`, false},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := middlewares.GetReqWithClientConfig(tt.config, httptest.NewRequest("GET", "https://7searc.com/", nil))
			if got := articleTitleSuffixFromConfig(middlewares.GetClientConfig(req.Context())); got != tt.want {
				t.Fatalf("articleTitleSuffixFromConfig() = %v, want %v", got, tt.want)
			}
		})
	}
	if !articleTitleSuffixFromConfig(nil) {
		t.Fatalf("articleTitleSuffixFromConfig(nil) = false, want true")
	}
}

func TestApplyOgDefaults(t *testing.T) {
	config := middlewares.GetClientConfig(middlewares.GetReqWithClientConfig(`{
		"displayName": "BodyTheory",
		"logo_url": "https://bodytheory.com/img/bodytheory-logo.png"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/", nil)).Context())

	t.Run("fills in site-wide defaults when unset", func(t *testing.T) {
		vars := &templateVars{}
		applyOgDefaults(vars, config)

		if vars.OgSiteName != "BodyTheory" {
			t.Fatalf("OgSiteName = %q", vars.OgSiteName)
		}
		if vars.OgLocale != "en_US" {
			t.Fatalf("OgLocale = %q", vars.OgLocale)
		}
		if vars.OgType != "website" {
			t.Fatalf("OgType = %q, want default 'website'", vars.OgType)
		}
		if vars.OgImage != "https://bodytheory.com/img/bodytheory-logo.png" {
			t.Fatalf("OgImage = %q, want logo fallback", vars.OgImage)
		}
		if vars.TwitterCard != "summary_large_image" {
			t.Fatalf("TwitterCard = %q", vars.TwitterCard)
		}
		if vars.TwitterImage != vars.OgImage {
			t.Fatalf("TwitterImage = %q, want to match OgImage fallback", vars.TwitterImage)
		}
	})

	t.Run("does not override page-specific values (e.g. article pages)", func(t *testing.T) {
		vars := &templateVars{OgType: "article", OgImage: "https://bodytheory.com/img/article.jpg"}
		applyOgDefaults(vars, config)

		if vars.OgType != "article" {
			t.Fatalf("OgType = %q, want unchanged 'article'", vars.OgType)
		}
		if vars.OgImage != "https://bodytheory.com/img/article.jpg" {
			t.Fatalf("OgImage = %q, want unchanged article image", vars.OgImage)
		}
	})

	t.Run("nil config or vars is a no-op", func(t *testing.T) {
		applyOgDefaults(nil, config)
		vars := &templateVars{}
		applyOgDefaults(vars, nil)
		if vars.OgSiteName != "" {
			t.Fatalf("expected no-op with nil config, got OgSiteName = %q", vars.OgSiteName)
		}
	})
}

// -----------------------------------------------------------------------------
// JSON-LD structured data
// -----------------------------------------------------------------------------

func TestOrganizationJSONLD(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory",
		"logo_url": "https://bodytheory.com/img/bodytheory-logo.png",
		"meta": {"description": "site-wide fallback description"},
		"seoMeta": {"home": {"description": "home page seo description"}}
	}`, httptest.NewRequest("GET", "https://bodytheory.com/", nil))
	req.Host = "bodytheory.com"

	// Even on a non-home page (a different vars.MetaDescription), the
	// Organization's description always mirrors seoMeta.home.description.
	vars := &templateVars{MetaDescription: "meta description of the current page"}
	got := organizationJSONLD(vars, middlewares.GetClientConfig(req.Context()), req)
	var parsed map[string]interface{}
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Fatalf("invalid JSON-LD: %v\n%s", err, got)
	}

	if parsed["@type"] != "Organization" {
		t.Fatalf("got @type %v, want Organization", parsed["@type"])
	}
	if parsed["name"] != "BodyTheory" {
		t.Fatalf("got name %v, want BodyTheory", parsed["name"])
	}
	if parsed["url"] != "https://bodytheory.com/" {
		t.Fatalf("got url %v, want https://bodytheory.com/", parsed["url"])
	}
	if parsed["logo"] != "https://bodytheory.com/img/bodytheory-logo.png" {
		t.Fatalf("got logo %v", parsed["logo"])
	}
	if parsed["description"] != "home page seo description" {
		t.Fatalf("got description %v, want seoMeta.home.description", parsed["description"])
	}
}

func TestOrganizationJSONLD_fallsBackToConfigDescription(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory",
		"meta": {"description": "site-wide fallback description"}
	}`, httptest.NewRequest("GET", "https://bodytheory.com/", nil))
	req.Host = "bodytheory.com"

	// No seoMeta.home configured — falls back to client_configs meta.description.
	got := organizationJSONLD(nil, middlewares.GetClientConfig(req.Context()), req)
	var parsed map[string]interface{}
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Fatalf("invalid JSON-LD: %v\n%s", err, got)
	}
	if parsed["description"] != "site-wide fallback description" {
		t.Fatalf("got description %v, want site-wide fallback description", parsed["description"])
	}
}

func TestOrganizationJSONLD_missingDisplayName(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{"siteId": "bodytheory"}`, httptest.NewRequest("GET", "/", nil))
	if got := organizationJSONLD(nil, middlewares.GetClientConfig(req.Context()), req); got != "" {
		t.Fatalf("got %q, want empty", got)
	}
}

func TestWebsiteJSONLD(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/", nil))
	req.Host = "bodytheory.com"

	got := websiteJSONLD(middlewares.GetClientConfig(req.Context()), req)
	var parsed map[string]interface{}
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Fatalf("invalid JSON-LD: %v\n%s", err, got)
	}

	if parsed["@type"] != "WebSite" {
		t.Fatalf("got @type %v, want WebSite", parsed["@type"])
	}
	action, ok := parsed["potentialAction"].(map[string]interface{})
	if !ok {
		t.Fatalf("potentialAction missing or wrong type: %v", parsed["potentialAction"])
	}
	if action["target"] != "https://bodytheory.com/search?term={search_term_string}" {
		t.Fatalf("got target %v", action["target"])
	}
}

func TestBreadcrumbJSONLD(t *testing.T) {
	// Fewer than 2 items (e.g. blog homepage) renders nothing.
	if got := breadcrumbJSONLD(nil); got != "" {
		t.Fatalf("got %q, want empty for nil items", got)
	}
	if got := breadcrumbJSONLD([]breadcrumbItem{{Name: "Home", URL: "https://bodytheory.com/"}}); got != "" {
		t.Fatalf("got %q, want empty for single item", got)
	}

	got := breadcrumbJSONLD([]breadcrumbItem{
		{Name: "Home", URL: "https://bodytheory.com/"},
		{Name: "Fitness", URL: "https://bodytheory.com/fitness"},
		{Name: "Some Article", URL: "https://bodytheory.com/fitness/123-some-article"},
	})

	var parsed struct {
		Type            string `json:"@type"`
		ItemListElement []struct {
			Position int    `json:"position"`
			Name     string `json:"name"`
			Item     string `json:"item"`
		} `json:"itemListElement"`
	}
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Fatalf("invalid JSON-LD: %v\n%s", err, got)
	}
	if parsed.Type != "BreadcrumbList" {
		t.Fatalf("got @type %v, want BreadcrumbList", parsed.Type)
	}
	if len(parsed.ItemListElement) != 3 {
		t.Fatalf("got %d items, want 3", len(parsed.ItemListElement))
	}
	if parsed.ItemListElement[1].Position != 2 || parsed.ItemListElement[1].Name != "Fitness" {
		t.Fatalf("unexpected second item: %+v", parsed.ItemListElement[1])
	}
}

func TestWebPageJSONLD(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory",
		"logo_url": "https://bodytheory.com/img/bodytheory-logo.png"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/fitness", nil))
	req.Host = "bodytheory.com"

	vars := &templateVars{
		PageTitle:       "Fitness - BodyTheory",
		OgTitle:         "Fitness",
		MetaDescription: "Browse fitness articles",
		CanonicalUrl:    "https://bodytheory.com/fitness",
	}

	got := webPageJSONLD(vars, middlewares.GetClientConfig(req.Context()), req)
	var parsed map[string]interface{}
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Fatalf("invalid JSON-LD: %v\n%s", err, got)
	}

	if parsed["name"] != "Fitness" {
		t.Fatalf("got name %v, want OgTitle 'Fitness'", parsed["name"])
	}
	if parsed["url"] != "https://bodytheory.com/fitness" {
		t.Fatalf("got url %v", parsed["url"])
	}
	publisher, ok := parsed["publisher"].(map[string]interface{})
	if !ok {
		t.Fatalf("publisher missing or wrong type: %v", parsed["publisher"])
	}
	logo, ok := publisher["logo"].(map[string]interface{})
	if !ok || logo["url"] != "https://bodytheory.com/img/bodytheory-logo.png" {
		t.Fatalf("unexpected publisher.logo: %v", publisher["logo"])
	}
}

func TestCollectionPageJSONLD(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/fitness", nil))
	req.Host = "bodytheory.com"

	vars := &templateVars{
		PageTitle:    "Fitness - BodyTheory",
		OgTitle:      "Fitness",
		CanonicalUrl: "https://bodytheory.com/fitness",
	}

	got := collectionPageJSONLD(vars, middlewares.GetClientConfig(req.Context()), req)
	var parsed map[string]interface{}
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Fatalf("invalid JSON-LD: %v\n%s", err, got)
	}
	if parsed["@type"] != "CollectionPage" {
		t.Fatalf("got @type %v, want CollectionPage", parsed["@type"])
	}
}

func TestArticleJSONLD(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory",
		"logo_url": "https://bodytheory.com/img/bodytheory-logo.png"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/fitness/123-some-article", nil))
	req.Host = "bodytheory.com"

	vars := &templateVars{
		PageTitle:            "Some Article - BodyTheory",
		OgTitle:              "Some Article",
		MetaDescription:      "An article about fitness",
		CanonicalUrl:         "https://bodytheory.com/fitness/123-some-article",
		OgImage:              "https://bodytheory.com/img/article.jpg",
		ArticlePublishedTime: "2026-01-01T00:00:00Z",
		ArticleSection:       "Fitness",
		MetaAuthor:           "Jane Doe",
	}

	got := articleJSONLD(vars, middlewares.GetClientConfig(req.Context()), req)
	var parsed map[string]interface{}
	if err := json.Unmarshal([]byte(got), &parsed); err != nil {
		t.Fatalf("invalid JSON-LD: %v\n%s", err, got)
	}
	if parsed["@type"] != "Article" {
		t.Fatalf("got @type %v, want Article", parsed["@type"])
	}
	if parsed["headline"] != "Some Article" {
		t.Fatalf("got headline %v", parsed["headline"])
	}
	if parsed["datePublished"] != "2026-01-01T00:00:00Z" {
		t.Fatalf("got datePublished %v", parsed["datePublished"])
	}
	author, ok := parsed["author"].(map[string]interface{})
	if !ok || author["@type"] != "Person" || author["name"] != "Jane Doe" {
		t.Fatalf("unexpected author: %v", parsed["author"])
	}
	mainEntity, ok := parsed["mainEntityOfPage"].(map[string]interface{})
	if !ok || mainEntity["@id"] != "https://bodytheory.com/fitness/123-some-article" {
		t.Fatalf("unexpected mainEntityOfPage: %v", parsed["mainEntityOfPage"])
	}
}

func TestApplyStructuredData_homepageHasNoBreadcrumbs(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/", nil))
	req.Host = "bodytheory.com"

	vars := &templateVars{PageTitle: "BodyTheory", CanonicalUrl: "https://bodytheory.com/"}
	applyStructuredData(vars, middlewares.GetClientConfig(req.Context()), req, nil)

	if vars.OrganizationSchema == "" {
		t.Fatal("expected OrganizationSchema to be set")
	}
	if vars.WebsiteSchema == "" {
		t.Fatal("expected WebsiteSchema to be set")
	}
	if vars.WebPageSchema == "" {
		t.Fatal("expected WebPageSchema to be set")
	}
	if vars.BreadcrumbSchema != "" {
		t.Fatalf("expected no BreadcrumbSchema on the homepage, got %s", vars.BreadcrumbSchema)
	}
}

func TestApplyHomepageStructuredData(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/", nil))
	req.Host = "bodytheory.com"

	vars := &templateVars{PageTitle: "BodyTheory", CanonicalUrl: "https://bodytheory.com/"}
	applyHomepageStructuredData(vars, middlewares.GetClientConfig(req.Context()), req)

	if vars.OrganizationSchema == "" {
		t.Fatal("expected OrganizationSchema to be set")
	}
	if vars.WebsiteSchema == "" {
		t.Fatal("expected WebsiteSchema to be set")
	}
	if vars.WebPageSchema != "" {
		t.Fatalf("expected no WebPageSchema on the homepage, got %s", vars.WebPageSchema)
	}
	if vars.BreadcrumbSchema != "" {
		t.Fatalf("expected no BreadcrumbSchema on the homepage, got %s", vars.BreadcrumbSchema)
	}
}

func TestApplyCategoryStructuredData(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/fitness", nil))
	req.Host = "bodytheory.com"

	vars := &templateVars{PageTitle: "Fitness - BodyTheory", CanonicalUrl: "https://bodytheory.com/fitness"}
	applyCategoryStructuredData(vars, middlewares.GetClientConfig(req.Context()), req, []breadcrumbItem{
		{Name: "Home", URL: "https://bodytheory.com/"},
		{Name: "Fitness", URL: "https://bodytheory.com/fitness"},
	})

	if vars.OrganizationSchema != "" {
		t.Fatalf("expected no OrganizationSchema on category pages, got %s", vars.OrganizationSchema)
	}
	if vars.WebsiteSchema != "" {
		t.Fatalf("expected no WebsiteSchema on category pages, got %s", vars.WebsiteSchema)
	}
	if vars.BreadcrumbSchema == "" {
		t.Fatal("expected BreadcrumbSchema to be set")
	}
	var parsed map[string]interface{}
	if err := json.Unmarshal([]byte(vars.WebPageSchema), &parsed); err != nil {
		t.Fatalf("invalid WebPageSchema JSON-LD: %v\n%s", err, vars.WebPageSchema)
	}
	if parsed["@type"] != "CollectionPage" {
		t.Fatalf("got @type %v, want CollectionPage", parsed["@type"])
	}
}

func TestApplyArticleStructuredData(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"siteId": "bodytheory",
		"displayName": "BodyTheory"
	}`, httptest.NewRequest("GET", "https://bodytheory.com/fitness/123-some-article", nil))
	req.Host = "bodytheory.com"

	vars := &templateVars{
		PageTitle:            "Some Article - BodyTheory",
		OgTitle:              "Some Article",
		CanonicalUrl:         "https://bodytheory.com/fitness/123-some-article",
		ArticlePublishedTime: "2026-01-01T00:00:00Z",
	}
	applyArticleStructuredData(vars, middlewares.GetClientConfig(req.Context()), req, []breadcrumbItem{
		{Name: "Home", URL: "https://bodytheory.com/"},
		{Name: "Fitness", URL: "https://bodytheory.com/fitness"},
		{Name: "Some Article", URL: "https://bodytheory.com/fitness/123-some-article"},
	})

	if vars.OrganizationSchema != "" {
		t.Fatalf("expected no OrganizationSchema on article pages, got %s", vars.OrganizationSchema)
	}
	if vars.WebsiteSchema != "" {
		t.Fatalf("expected no WebsiteSchema on article pages, got %s", vars.WebsiteSchema)
	}
	if vars.BreadcrumbSchema == "" {
		t.Fatal("expected BreadcrumbSchema to be set")
	}
	if vars.WebPageSchema == "" {
		t.Fatal("expected WebPageSchema to be set")
	}
	if vars.ArticleSchema == "" {
		t.Fatal("expected ArticleSchema to be set")
	}
}

func TestServeTrailingSlashRedirect(t *testing.T) {
	for path, want := range map[string]string{
		"/fitness/?page=2":         "/fitness?page=2",
		"/kids-health/treatments/": "/kids-health/treatments",
	} {
		rec := httptest.NewRecorder()
		if !serveTrailingSlashRedirect(rec, httptest.NewRequest(http.MethodGet, path, nil)) {
			t.Fatalf("%s: no redirect, want 301", path)
		}
		if rec.Code != http.StatusMovedPermanently {
			t.Fatalf("%s: status = %d, want 301", path, rec.Code)
		}
		if got := rec.Header().Get("Location"); got != want {
			t.Fatalf("%s: Location = %q, want %q", path, got, want)
		}
		if got := rec.Header().Get("Cache-Control"); got != "public, max-age=3600" {
			t.Fatalf("%s: Cache-Control = %q, want %q", path, got, "public, max-age=3600")
		}
	}
}

func TestServeTrailingSlashRedirectSkipsUnsafeOrUnmatchedPaths(t *testing.T) {
	// Raw request targets, as sent on the wire (%5C = "\", %09 = tab).
	for _, path := range []string{"/a/b/c/d/", "///", "//evil.com/", "/~/abc/", "/%5Cevil.test/", "/%5C%5Cevil.test/", "/%5C/evil.test/", "/%09/evil.test/"} {
		rec := httptest.NewRecorder()
		if serveTrailingSlashRedirect(rec, httptest.NewRequest(http.MethodGet, path, nil)) {
			t.Fatalf("%s: redirected to %q, want no redirect", path, rec.Header().Get("Location"))
		}
	}
}

func TestNormalizeMetaDescription(t *testing.T) {
	// Shared with oos-singlecube's articleMetaDescription tests.
	cases := map[string]string{
		"Start functional training today.  Read more ": "Start functional training today.",
		"Start functional training today. read more":   "Start functional training today.",
		"Start functional training today. Read More":   "Start functional training today.",
		"Start functional training today. READ MORE":   "Start functional training today.",
		"  Plain description  ":                        "Plain description",
		"Read more":                                    "",
		"Learn more about reading":                     "Learn more about reading",
		// Only stripped after a finished sentence; real sentences are kept.
		"Kids should read more":               "Kids should read more",
		"Read more about this on the website": "Read more about this on the website",
		"Is it worth it? Read more":           "Is it worth it?",
		"Tough times… Read more":              "Tough times…",
	}
	for in, want := range cases {
		if got := normalizeMetaDescription(in); got != want {
			t.Errorf("normalizeMetaDescription(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestBuildArticleDetailPathNeverStartsWithDoubleSlash(t *testing.T) {
	got := buildArticleDetailPath("!!!", "", "1090", "Food And Wine")
	if want := "/article/1090-food-and-wine"; got != want {
		t.Fatalf("got %q, want %q", got, want)
	}
}

func TestRedirectLocation(t *testing.T) {
	cases := []struct{ path, query, fragment, want string }{
		{"/fitness", "", "", "/fitness"},
		{"/fitness", "page=2", "", "/fitness?page=2"},
		{"/wine-101/wine-types/1778071-spicy-wine", "utm_source=x", "", "/wine-101/wine-types/1778071-spicy-wine?utm_source=x"},
		{"/fitness/1775223-functional-training", "ref=a", "tips", "/fitness/1775223-functional-training?ref=a#tips"},
		// Characters a browser could turn into another host are escaped.
		{`/\evil.test`, "", "", "/%5Cevil.test"},
		{"/\t/evil.test", "", "", "/%09/evil.test"},
	}
	for _, tt := range cases {
		if got := redirectLocation(tt.path, tt.query, tt.fragment); got != tt.want {
			t.Errorf("redirectLocation(%q, %q, %q) = %q, want %q", tt.path, tt.query, tt.fragment, got, tt.want)
		}
	}
}

func TestParseSubcategoryPath(t *testing.T) {
	tests := []struct {
		path        string
		wantCat     string
		wantSubcat  string
		wantMatched bool
	}{
		{"/wine-101/wine-types", "wine-101", "wine-types", true},
		{"/kids-health/treatments/", "kids-health", "treatments", true},
		// article slugs start with the numeric id
		{"/wine-tips/1778500-wine-faults", "", "", false},
		// reserved first segment
		{"/articles/category", "", "", false},
		// only plain slug segments match, so junk isn't served as a second URL
		{"/~/abc", "", "", false},
		{"/~/abc/", "", "", false},
		{"/Wine-101/wine-types", "", "", false},
		{"/wine-101/wine_types", "", "", false},
		{"//evil.com", "", "", false},
		{"/a/b/c", "", "", false},
	}
	for _, tt := range tests {
		cat, sub, ok := parseSubcategoryPath(tt.path)
		if cat != tt.wantCat || sub != tt.wantSubcat || ok != tt.wantMatched {
			t.Errorf("parseSubcategoryPath(%q) = (%q, %q, %v), want (%q, %q, %v)",
				tt.path, cat, sub, ok, tt.wantCat, tt.wantSubcat, tt.wantMatched)
		}
	}
}

// -----------------------------------------------------------------------------
// Internal links inside CMS article content
// -----------------------------------------------------------------------------

func TestRewriteInternalLinks(t *testing.T) {
	// Canonical paths the CMS would give for the linked article IDs.
	paths := map[string]string{
		"1760498": "/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you",
		"1766094": "/weight-loss-tips/1766094-top-ways-to-boost-metabolism-for-fast-natural-weight-loss",
		"26165":   "/wine-101/wine-regions/26165-the-top-pinot-noir-regions-to-visit-for-wine-lovers",
	}
	resolve := func(id string) string { return paths[id] }

	tests := []struct {
		name    string
		content string
		want    string
	}{
		{
			name:    "old live category, outdated slug and trailing slash",
			content: `<p>Try <a href="https://www.centerweightloss.com/weight-loss/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you/">these drinks</a>.</p>`,
			want:    `<p>Try <a href="/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you">these drinks</a>.</p>`,
		},
		{
			name:    "legacy /articles/ prefix",
			content: `<a href="https://www.centerweightloss.com/articles/1766094-top-ways-to-boost-metabolism/">x</a>`,
			want:    `<a href="/weight-loss-tips/1766094-top-ways-to-boost-metabolism-for-fast-natural-weight-loss">x</a>`,
		},
		{
			name:    "bare domain, http and missing subcategory",
			content: `<a target="_blank" href='http://centerweightloss.com/wine-101/26165-pinot'>x</a>`,
			want:    `<a target="_blank" href="/wine-101/wine-regions/26165-the-top-pinot-noir-regions-to-visit-for-wine-lovers">x</a>`,
		},
		{
			name:    "encoded old subcategory segment",
			content: `<a href="https://www.centerweightloss.com/raising-kids/Raising%20Kids/1760498-x">x</a>`,
			want:    `<a href="/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you">x</a>`,
		},
		{
			name:    "domain written without a scheme",
			content: `<a href="centerweightloss.com/weight-loss/1760498-x">x</a>`,
			want:    `<a href="/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you">x</a>`,
		},
		{
			name:    "utm params dropped, other params and fragment kept",
			content: `<a href="https://centerweightloss.com/articles/1760498-x?utm_source=chatgpt.com&amp;ref=a#tips">x</a>`,
			want:    `<a href="/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you?ref=a#tips">x</a>`,
		},
		{
			name:    "homepage and category links",
			content: `<a href="http://centerweightloss.com">home</a> <a href="https://centerweightloss.com/?utm_source=gemini">home</a> <a href="https://www.centerweightloss.com/dieting-tips/">cat</a> <a href="https://centerweightloss.com/wine-101/wine-types/">sub</a>`,
			want:    `<a href="/">home</a> <a href="/">home</a> <a href="/dieting-tips">cat</a> <a href="/wine-101/wine-types">sub</a>`,
		},
		{
			name:    "static page links, including aliases",
			content: `<a href="https://www.centerweightloss.com/about/">a</a> <a href="https://centerweightloss.com/contactus">b</a> <a href="https://centerweightloss.com/privacy/">c</a>`,
			want:    `<a href="/about">a</a> <a href="/contactus">b</a> <a href="/privacy">c</a>`,
		},
		{
			name:    "article the CMS can't resolve is left as written",
			content: `<a href="https://www.centerweightloss.com/articles/999-gone/">x</a>`,
			want:    `<a href="https://www.centerweightloss.com/articles/999-gone/">x</a>`,
		},
		{
			name:    "external, javascript, plain text and other-site links untouched",
			content: `<a href="https://www.youtube.com/watch?v=1">a</a><a href="javascript:void(0)">b</a><a href="Unlock The Secrets Of Wine">c</a><a href="https://pointwines.com/wine-101/26165-x">d</a><a href="mailto:hi@centerweightloss.com">e</a>`,
			want:    `<a href="https://www.youtube.com/watch?v=1">a</a><a href="javascript:void(0)">b</a><a href="Unlock The Secrets Of Wine">c</a><a href="https://pointwines.com/wine-101/26165-x">d</a><a href="mailto:hi@centerweightloss.com">e</a>`,
		},
		{
			name:    "junk own-site paths untouched, never turned into another site's URL",
			content: `<a href="https://centerweightloss.com//evil.com/">a</a><a href="https://centerweightloss.com/~/abc/">b</a><a href="https://centerweightloss.com/Fitness/">c</a><a href="https://centerweightloss.com/a/b/c/d/1760498-x">d</a>`,
			want:    `<a href="https://centerweightloss.com//evil.com/">a</a><a href="https://centerweightloss.com/~/abc/">b</a><a href="https://centerweightloss.com/Fitness/">c</a><a href="https://centerweightloss.com/a/b/c/d/1760498-x">d</a>`,
		},
		{
			name:    "already-final links are left byte for byte",
			content: `<a href='/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you'>x</a><a href="/dieting-tips">y</a>`,
			want:    `<a href='/weight-loss-tips/1760498-easy-homemade-weight-loss-drinks-for-a-healthier-you'>x</a><a href="/dieting-tips">y</a>`,
		},
		{
			name:    "data-href and text mentioning href are not links",
			content: `<div data-href="https://centerweightloss.com/articles/1760498-x/">use href="..."</div>`,
			want:    `<div data-href="https://centerweightloss.com/articles/1760498-x/">use href="..."</div>`,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := rewriteInternalLinks(tt.content, "centerweightloss.com", resolve); got != tt.want {
				t.Fatalf("got\n  %s\nwant\n  %s", got, tt.want)
			}
		})
	}
}

func TestRewriteInternalLinksResolvesEachArticleOnce(t *testing.T) {
	var mu sync.Mutex
	calls := map[string]int{}
	resolve := func(id string) string {
		mu.Lock()
		calls[id]++
		mu.Unlock()
		return "/fitness/" + id + "-x"
	}
	content := `<a href="https://bodytheory.com/fitness/1-a">a</a><a href="https://bodytheory.com/health/1-a/">b</a><a href="https://bodytheory.com/fitness/2-b">c</a>`

	got := rewriteInternalLinks(content, "bodytheory.com", resolve)

	want := `<a href="/fitness/1-x">a</a><a href="/fitness/1-x">b</a><a href="/fitness/2-x">c</a>`
	if got != want {
		t.Fatalf("got %s, want %s", got, want)
	}
	if calls["1"] != 1 || calls["2"] != 1 {
		t.Fatalf("lookups = %v, want one per article", calls)
	}
}

func TestRewriteInternalLinksWithoutSiteDomain(t *testing.T) {
	content := `<a href="https://bodytheory.com/fitness/1-a/">a</a>`
	resolve := func(string) string {
		t.Fatal("no lookup expected without a site domain")
		return ""
	}
	if got := rewriteInternalLinks(content, "", resolve); got != content {
		t.Fatalf("got %s, want content unchanged", got)
	}
}

func TestWithoutUTMParams(t *testing.T) {
	tests := []struct{ in, want string }{
		{"", ""},
		{"ref=a", "ref=a"},
		{"utm_source=chatgpt.com", ""},
		{"utm_source=chatgpt.com&ref=a", "ref=a"},
		// Other params keep their order and encoding.
		{"z=1&UTM_Medium=x&a=hello%20world&b=x+y", "z=1&a=hello%20world&b=x+y"},
		// utm_ inside a value (or a key that only contains it) isn't a utm param.
		{"ref=utm_source&b=2", "ref=utm_source&b=2"},
		{"xutm_a=1", "xutm_a=1"},
	}
	for _, tt := range tests {
		if got := withoutUTMParams(tt.in); got != tt.want {
			t.Errorf("withoutUTMParams(%q) = %q, want %q", tt.in, got, tt.want)
		}
	}
}

func TestOwnSitePagePath(t *testing.T) {
	tests := []struct{ path, want string }{
		{"", "/"},
		{"/", "/"},
		{"/about/", "/about"},
		{"/aboutus", "/aboutus"},
		{"/search", "/search"},
		{"/shop/", "/shop"},
		{"/fitness/", "/fitness"},
		{"/wine-101/wine-types/", "/wine-101/wine-types"},
		// Not a page: left for the caller to keep as written.
		{"/About/", ""},
		{"/about/team", ""},
		{"/a/b/c", ""},
		{"//evil.com/", ""},
		{`/\evil.com/`, ""},
	}
	for _, tt := range tests {
		if got := ownSitePagePath(tt.path); got != tt.want {
			t.Errorf("ownSitePagePath(%q) = %q, want %q", tt.path, got, tt.want)
		}
	}
}

func TestLegacySearchRedirectQuery(t *testing.T) {
	tests := []struct {
		query  string
		want   string
		wantOK bool
	}{
		{"keyword=claim", "term=claim", true},
		{"keyword=claim&page=2", "term=claim&page=2", true},
		{"keyword=claims+%26+coverage&utm_source=x", "term=claims+%26+coverage&utm_source=x", true},
		{"keyword=", "term=", true},
		// Other params keep their order and encoding.
		{"page=2&keyword=car%20loans&utm_source=x", "page=2&term=car%20loans&utm_source=x", true},
		// Already on the live sites' form, or both present: no redirect.
		{"term=alo+yoga", "", false},
		{"keyword=claim&term=other", "", false},
		{"", "", false},
		{"page=2", "", false},
		// Unparseable queries are left alone.
		{"keyword=%zz", "", false},
		// The legacy magazine sites' ?search= too; with both names the first wins.
		{"search=rings&page=2", "term=rings&page=2", true},
		{"keyword=a&search=b", "term=a", true},
		{"search=b&term=c", "", false},
	}
	for _, tt := range tests {
		got, ok := legacySearchRedirectQuery(tt.query)
		if got != tt.want || ok != tt.wantOK {
			t.Errorf("legacySearchRedirectQuery(%q) = (%q, %v), want (%q, %v)", tt.query, got, ok, tt.want, tt.wantOK)
		}
	}
}

func TestServeLegacySearchRedirect(t *testing.T) {
	rec := httptest.NewRecorder()
	if !serveLegacySearchRedirect(rec, httptest.NewRequest(http.MethodGet, "/search?keyword=claim&page=2", nil)) {
		t.Fatal("no redirect, want 301")
	}
	if rec.Code != http.StatusMovedPermanently {
		t.Fatalf("status = %d, want 301", rec.Code)
	}
	if got, want := rec.Header().Get("Location"), "/search?term=claim&page=2"; got != want {
		t.Fatalf("Location = %q, want %q", got, want)
	}
	if got := rec.Header().Get("Cache-Control"); got != "public, max-age=3600" {
		t.Fatalf("Cache-Control = %q, want %q", got, "public, max-age=3600")
	}

	rec = httptest.NewRecorder()
	if serveLegacySearchRedirect(rec, httptest.NewRequest(http.MethodGet, "/search?term=alo+yoga", nil)) {
		t.Fatalf("redirected to %q, want no redirect", rec.Header().Get("Location"))
	}
}

func TestOgImageType(t *testing.T) {
	cases := map[string]string{
		"https://prod-cms-image-contents.s3.us-west-1.amazonaws.com/a/heart.png":         "image/png",
		"https://prod-cms-image-contents.s3.us-west-1.amazonaws.com/a/hero.JPG":          "image/jpeg",
		"https://prod-cms-image-contents.s3.us-west-1.amazonaws.com/a/hero.jpeg?w=800":   "image/jpeg",
		"https://prod-cms-image-contents.s3.us-west-1.amazonaws.com/a/hero.webp":         "image/webp",
		"https://prod-cms-image-contents.s3.us-west-1.amazonaws.com/a/no-extension":      "image/jpeg",
		"https://prod-cms-image-contents.s3.us-west-1.amazonaws.com/a/file.pdf":          "image/jpeg",
		"https://prod-cms-image-contents.s3.us-west-1.amazonaws.com/a/favicon%20(1).png": "image/png",
	}
	for in, want := range cases {
		if got := ogImageType(in); got != want {
			t.Errorf("ogImageType(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestCategoryKeywords(t *testing.T) {
	cases := []struct{ category, sub, want string }{
		{"Places To Go", "", "Places To Go"},
		{"Wine 101", "Wine Regions", "Wine 101, Wine Regions"},
		{"", "Wine Regions", ""},
	}
	for _, c := range cases {
		if got := categoryKeywords(c.category, c.sub); got != c.want {
			t.Errorf("categoryKeywords(%q, %q) = %q, want %q", c.category, c.sub, got, c.want)
		}
	}
}

func TestArticleURLOptions(t *testing.T) {
	configWith := func(shared map[string]interface{}) *middlewares.ClientConfig {
		return &middlewares.ClientConfig{ViperConfig: viper.New(), Raw: map[string]interface{}{"shared": shared}}
	}
	if got := articleURLOptionsFromConfig(nil); got != (articleURLOptions{WithSubcategory: true}) {
		t.Fatalf("nil config: %+v", got)
	}
	if got := articleURLOptionsFromConfig(configWith(map[string]interface{}{})); got != (articleURLOptions{WithSubcategory: true}) {
		t.Fatalf("defaults: %+v", got)
	}
	if got := articleURLOptionsFromConfig(configWith(map[string]interface{}{"articleUrlSubcategory": false, "articleSlugFromTitle": true, "articleSlugAmpersandAsAnd": true})); got != (articleURLOptions{SlugFromTitle: true, AmpersandAsAnd: true}) {
		t.Fatalf("both set: %+v", got)
	}

	meta := articlePageMeta{Category: "Beauty", SubCategory: "Hair", SlugTitle: "hair care routine", CMSSlugTitle: "hair care routine", CMSTitle: "How to Build the Perfect Hair Care Routine?"}
	// With the subcategory (default): the flat live URL redirects to the nested one.
	if got := articleCanonicalRedirectPath(forArticleURL(meta, articleURLOptions{WithSubcategory: true}), "1780966", "/beauty/1780966-hair-care-routine"); got != "/beauty/hair/1780966-hair-care-routine" {
		t.Errorf("with subcategory: got %q", got)
	}
	// Without (womenwire): the flat URL is canonical, and the nested one redirects to it.
	flat := articleURLOptions{SlugFromTitle: true}
	if got := articleCanonicalRedirectPath(forArticleURL(meta, flat), "1780966", "/beauty/1780966-hair-care-routine"); got != "" {
		t.Errorf("without subcategory: flat URL should be canonical, got redirect %q", got)
	}
	if got := articleCanonicalRedirectPath(forArticleURL(meta, flat), "1780966", "/beauty/hair/1780966-hair-care-routine"); got != "/beauty/1780966-hair-care-routine" {
		t.Errorf("without subcategory: nested URL should redirect to the flat one, got %q", got)
	}
	// No CMS slug_title: the meta title by default, the title with SlugFromTitle (a slug_title always wins).
	noSlug := articlePageMeta{Category: "Fashion", SlugTitle: "Hair Caring Tips for Colored Hair", CMSTitle: "Care Your Colored Hair!"}
	if got := canonicalArticlePath(forArticleURL(noSlug, articleURLOptions{WithSubcategory: true}), "8929"); got != "/fashion/8929-hair-caring-tips-for-colored-hair" {
		t.Errorf("default slug source: %q", got)
	}
	if got := canonicalArticlePath(forArticleURL(noSlug, flat), "8929"); got != "/fashion/8929-care-your-colored-hair" {
		t.Errorf("slug from title: %q", got)
	}
}

func TestArticleTitlePattern(t *testing.T) {
	configWith := func(raw map[string]interface{}) *middlewares.ClientConfig {
		v := viper.New()
		if err := v.MergeConfigMap(raw); err != nil {
			t.Fatal(err)
		}
		return &middlewares.ClientConfig{ViperConfig: v, Raw: raw}
	}
	withPattern := func(title string) *middlewares.ClientConfig {
		return configWith(map[string]interface{}{"seoMeta": map[string]interface{}{"articleDetails": map[string]interface{}{"title": title}}})
	}
	// Key case doesn't matter, as for the other seoMeta entries (and the frontend's getSeoMetaEntry).
	lower := configWith(map[string]interface{}{"seometa": map[string]interface{}{"articledetails": map[string]interface{}{"title": "{headline}"}}})
	if got := articleTitlePattern(lower); got != "{headline}" {
		t.Errorf("lowercase keys: pattern = %q", got)
	}
	for _, p := range []string{"Gaycommunity : {title}", "Gaycommunity : {Headline}", "{headline}"} {
		if got := articleTitlePattern(withPattern(p)); got != p {
			t.Errorf("pattern %q = %q", p, got)
		}
	}
	cases := []struct{ pattern, seo, headline, want string }{
		{"Gaycommunity : {Headline}", "Love Stories to Read", "Best LGBTQ Romance Books: 15 Queer Love Stories to Read", "Gaycommunity : Best LGBTQ Romance Books: 15 Queer Love Stories To Read"},
		{"{headline}", "Eye Makeup Looks | Womenwire", "Explore The Top 10 Eye Makeup Looks", "Explore The Top 10 Eye Makeup Looks"},
		{"{title} | Site", "SEO title", "", "SEO title | Site"},
		{"{headline}", "SEO title", "", "SEO title"},
	}
	for _, c := range cases {
		if got := expandArticleTitlePattern(c.pattern, c.seo, c.headline); got != c.want {
			t.Errorf("expand(%q) = %q, want %q", c.pattern, got, c.want)
		}
	}
	for _, c := range []*middlewares.ClientConfig{nil, configWith(map[string]interface{}{}), withPattern("Gaycommunity articles")} {
		if got := articleTitlePattern(c); got != "" {
			t.Errorf("no usable pattern: got %q", got)
		}
	}
}
