package routes

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

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

func TestBuildSitemapArticlePath(t *testing.T) {
	path := buildSitemapArticlePath(map[string]interface{}{
		"id":         float64(1775223),
		"meta_title": "Functional Training for Total Body Strength Results Guide",
		"category":   "Fitness",
	}, "Fitness", articleURLOptions{WithSubcategory: true})
	want := "/fitness/1775223-functional-training-for-total-body-strength-results-guide"
	if path != want {
		t.Fatalf("path = %q, want %q", path, want)
	}
}

func TestBuildSitemapArticlePath_WithSubcategory(t *testing.T) {
	path := buildSitemapArticlePath(map[string]interface{}{
		"id":           float64(1090),
		"meta_title":   "Food And Wine",
		"category":     "Wine 101",
		"sub_category": "Wine Regions",
	}, "Wine 101", articleURLOptions{WithSubcategory: true})
	want := "/wine-101/wine-regions/1090-food-and-wine"
	if path != want {
		t.Fatalf("path = %q, want %q", path, want)
	}
}

func TestBuildSitemapArticlePath_NullSubcategory(t *testing.T) {
	// sub_category is often present but null when the article has no subcategory.
	path := buildSitemapArticlePath(map[string]interface{}{
		"id":           float64(1775223),
		"meta_title":   "Functional Training",
		"category":     "Fitness",
		"sub_category": nil,
	}, "Fitness", articleURLOptions{WithSubcategory: true})
	want := "/fitness/1775223-functional-training"
	if path != want {
		t.Fatalf("path = %q, want %q", path, want)
	}
}

func TestExtractSitemapCategories_IncludesSubcategories(t *testing.T) {
	response := map[string]interface{}{
		"data": map[string]interface{}{
			"pointwines.com": []interface{}{
				map[string]interface{}{
					"cat_id":   "101",
					"cat_name": "Wine 101",
					"subcategories": []interface{}{
						map[string]interface{}{"id": float64(1090), "name": "Food And Wine"},
						map[string]interface{}{"id": float64(1089), "name": "Wine Regions"},
					},
				},
				map[string]interface{}{"cat_id": "100", "cat_name": "Articles"},
			},
		},
	}

	categories := extractSitemapCategories(response, "pointwines.com")
	if len(categories) != 2 {
		t.Fatalf("expected 2 categories, got %d", len(categories))
	}

	wine101 := categories[0]
	if wine101.Slug != "wine-101" {
		t.Fatalf("expected slug wine-101, got %q", wine101.Slug)
	}
	if len(wine101.Subcategories) != 2 {
		t.Fatalf("expected 2 subcategories, got %d", len(wine101.Subcategories))
	}
	if wine101.Subcategories[0].Slug != "food-and-wine" || wine101.Subcategories[1].Slug != "wine-regions" {
		t.Fatalf("unexpected subcategory slugs: %+v", wine101.Subcategories)
	}

	articles := categories[1]
	if len(articles.Subcategories) != 0 {
		t.Fatalf("expected no subcategories, got %+v", articles.Subcategories)
	}
}

func TestParseSitemapCategoryPath(t *testing.T) {
	cases := []struct {
		path string
		ok   bool
		slug string
	}{
		{"/sitemap_fitness.xml", true, "fitness"},
		{"/sitemap_wine-tips.xml", true, "wine-tips"},
		{"/sitemap_pages.xml", false, ""}, // dedicated route; not via catch-all
		{"/sitemap.xml", false, ""},
		{"/fitness", false, ""},
	}
	for _, tc := range cases {
		m := sitemapCategoryPathRe.FindStringSubmatch(tc.path)
		ok := m != nil && !strings.EqualFold(m[1], "pages")
		slug := ""
		if m != nil {
			slug = m[1]
		}
		if ok != tc.ok || (tc.ok && slug != tc.slug) {
			t.Errorf("path %q: ok=%v slug=%q, want ok=%v slug=%q", tc.path, ok, slug, tc.ok, tc.slug)
		}
	}
}

func TestSitemapPagesHandler(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/sitemap_pages.xml", nil)
	req.Host = "bodytheory.com"
	rr := httptest.NewRecorder()
	SitemapPagesHandler().ServeHTTP(rr, req)

	if rr.Code != http.StatusOK {
		t.Fatalf("status = %d", rr.Code)
	}
	body := rr.Body.String()
	for _, want := range []string{
		`https://bodytheory.com/`,
		`https://bodytheory.com/about`,
		`https://bodytheory.com/contact`,
		`https://bodytheory.com/privacy`,
		`https://bodytheory.com/terms`,
		`https://bodytheory.com/sitemap`,
		`<lastmod>`,
	} {
		if !strings.Contains(body, want) {
			t.Errorf("body missing %q\n%s", want, body)
		}
	}
	if ct := rr.Header().Get("Content-Type"); !strings.Contains(ct, "application/xml") {
		t.Errorf("Content-Type = %q", ct)
	}
}

func TestSitemapIndexAndCategoryHandlers(t *testing.T) {
	srv := newMockCMSServer(t, mockCMSData{
		categories: map[string]interface{}{
			"data": map[string]interface{}{
				"bodytheory.com": []interface{}{
					map[string]interface{}{
						"cat_id":   "1",
						"cat_name": "Fitness",
						"subcategories": []interface{}{
							map[string]interface{}{"id": float64(11), "name": "Strength Training"},
						},
					},
					map[string]interface{}{"cat_id": "2", "cat_name": "Wellness"},
					map[string]interface{}{"cat_id": "3", "cat_name": "Health"},
				},
			},
		},
		articlesByCategory: map[string][]map[string]interface{}{
			"1": {
				{
					"id":           "1775223",
					"meta_title":   "Functional Training for Total Body Strength Results Guide",
					"category":     "Fitness",
					"sub_category": "Strength Training",
					"publish_date": "2026-01-15",
					"is_index":     1,
				},
				{
					"id":         "999",
					"meta_title": "Hidden Article",
					"category":   "Fitness",
					"is_index":   0,
				},
			},
			"2": {},
			"3": {},
		},
	})
	teardown := withCMSService(t, srv)
	defer teardown()

	t.Run("index", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/sitemap.xml", nil)
		req.Host = "bodytheory.com"
		rr := httptest.NewRecorder()
		SitemapIndexHandler().ServeHTTP(rr, req)
		if rr.Code != http.StatusOK {
			t.Fatalf("status = %d body=%s", rr.Code, rr.Body.String())
		}
		body := rr.Body.String()
		for _, want := range []string{
			`https://bodytheory.com/sitemap_pages.xml`,
			`https://bodytheory.com/sitemap_fitness.xml`,
			`https://bodytheory.com/sitemap_wellness.xml`,
			`https://bodytheory.com/sitemap_health.xml`,
			`<sitemapindex`,
		} {
			if !strings.Contains(body, want) {
				t.Errorf("missing %q\n%s", want, body)
			}
		}
	})

	t.Run("category", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/sitemap_fitness.xml", nil)
		req.Host = "bodytheory.com"
		rr := httptest.NewRecorder()
		SitemapCategoryHandler("fitness").ServeHTTP(rr, req)
		if rr.Code != http.StatusOK {
			t.Fatalf("status = %d body=%s", rr.Code, rr.Body.String())
		}
		body := rr.Body.String()
		if !strings.Contains(body, "https://bodytheory.com/fitness") {
			t.Errorf("missing category loc\n%s", body)
		}
		wantSubcategory := "https://bodytheory.com/fitness/strength-training"
		if !strings.Contains(body, wantSubcategory) {
			t.Errorf("missing subcategory loc\n%s", body)
		}
		wantArticle := "https://bodytheory.com/fitness/strength-training/1775223-functional-training-for-total-body-strength-results-guide"
		if !strings.Contains(body, wantArticle) {
			t.Errorf("missing article loc\n%s", body)
		}
		if strings.Contains(body, "Hidden Article") || strings.Contains(body, "/999-") {
			t.Errorf("noindex article should be excluded\n%s", body)
		}
		if !strings.Contains(body, "<lastmod>2026-01-15</lastmod>") {
			t.Errorf("missing article lastmod\n%s", body)
		}
	})

	t.Run("unknown category 404", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/sitemap_unknown.xml", nil)
		req.Host = "bodytheory.com"
		rr := httptest.NewRecorder()
		SitemapCategoryHandler("unknown").ServeHTTP(rr, req)
		if rr.Code != http.StatusNotFound {
			t.Fatalf("status = %d, want 404", rr.Code)
		}
	})
}

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

	req := httptest.NewRequest(http.MethodGet, "/robots.txt", nil)
	req.Host = "bodytheory.com"
	rr := httptest.NewRecorder()
	RobotsTxtRouteHandler().ServeHTTP(rr, req)
	body := rr.Body.String()

	wants := []string{
		"User-agent: *",
		"Allow: /",
		"Disallow: /search?term=",
		"User-agent: GPTBot",
		"User-agent: ChatGPT-User",
		"User-agent: Google-Extended",
		"User-agent: ClaudeBot",
		"User-agent: anthropic-ai",
		"User-agent: PerplexityBot",
		"Sitemap: https://bodytheory.com/sitemap.xml",
	}
	for _, want := range wants {
		if !strings.Contains(body, want) {
			t.Fatalf("robots missing %q:\n%s", want, body)
		}
	}
	if strings.Contains(body, "Disallow: /\n") {
		t.Fatalf("prod host should not disallow all:\n%s", body)
	}
}

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

	req := httptest.NewRequest(http.MethodGet, "/robots.txt", nil)
	req.Host = "uat-bodytheory.imds.tv"
	rr := httptest.NewRecorder()
	RobotsTxtRouteHandler().ServeHTTP(rr, req)
	body := rr.Body.String()
	if !strings.Contains(body, "Disallow: /") {
		t.Fatalf("UAT should disallow:\n%s", body)
	}
	if strings.Contains(body, "Sitemap:") {
		t.Fatalf("UAT should not advertise Sitemap:\n%s", body)
	}
}

// requestPublicBaseURL and canonicalURL are tested in seo_test.go, where
// they now live alongside the rest of the SEO helpers.

func TestTryServeSitemapXML(t *testing.T) {
	srv := newMockCMSServer(t, mockCMSData{
		categories: map[string]interface{}{
			"data": map[string]interface{}{
				"bodytheory.com": []interface{}{
					map[string]interface{}{"cat_id": "1", "cat_name": "Fitness"},
				},
			},
		},
		articlesByCategory: map[string][]map[string]interface{}{
			"1": {},
		},
	})
	teardown := withCMSService(t, srv)
	defer teardown()

	req := httptest.NewRequest(http.MethodGet, "/sitemap_fitness.xml", nil)
	req.Host = "bodytheory.com"
	rr := httptest.NewRecorder()
	if !tryServeSitemapXML(rr, req) {
		t.Fatal("expected tryServeSitemapXML to handle path")
	}
	if rr.Code != http.StatusOK {
		t.Fatalf("status = %d", rr.Code)
	}
}

func TestBuildSitemapArticlePath_NeverStartsWithDoubleSlash(t *testing.T) {
	path := buildSitemapArticlePath(map[string]interface{}{
		"id":         "1090",
		"slug_title": "Food And Wine",
		"category":   "!!!",
	}, "", articleURLOptions{WithSubcategory: true})
	if want := "/article/1090-food-and-wine"; path != want {
		t.Fatalf("path = %q, want %q", path, want)
	}
}

func TestSitemapPagesHandler_ConfiguredPages(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{
		"sitemapPages": ["/", "/about", "/privacy", "/terms", "https://evil.test/", "/nope"]
	}`, httptest.NewRequest(http.MethodGet, "/sitemap_pages.xml", nil))
	req.Host = "7searc.com"
	rr := httptest.NewRecorder()
	SitemapPagesHandler().ServeHTTP(rr, req)

	if rr.Code != http.StatusOK {
		t.Fatalf("status = %d", rr.Code)
	}
	body := rr.Body.String()
	var locs []string
	for _, part := range strings.Split(body, "<loc>")[1:] {
		locs = append(locs, part[:strings.Index(part, "</loc>")])
	}
	want := []string{"https://7searc.com", "https://7searc.com/about", "https://7searc.com/privacy", "https://7searc.com/terms", "https://7searc.com/sitemap"}
	if strings.Join(locs, " ") != strings.Join(want, " ") {
		t.Fatalf("locs = %v, want %v", locs, want)
	}
}

func TestSitemapPagesFromConfig_AddsSitemapAndAdvertisers(t *testing.T) {
	pages := func(cfg string) string {
		req := middlewares.GetReqWithClientConfig(cfg, httptest.NewRequest(http.MethodGet, "/sitemap_pages.xml", nil))
		return strings.Join(sitemapPagesFromConfig(middlewares.GetClientConfig(req.Context())), " ")
	}
	if got, want := pages(`{"sitemapPages": ["/", "/about"], "pages": {"forAdvertisers": {}}}`), "/ /about /sitemap /for_advertisers"; got != want {
		t.Errorf("site with an advertisers page: %q, want %q", got, want)
	}
	if got, want := pages(`{"sitemapPages": ["/", "/about"]}`), "/ /about /sitemap"; got != want {
		t.Errorf("site without an advertisers page: %q, want %q", got, want)
	}
	if got, want := pages(`{"sitemapPages": ["/", "/sitemap", "/for_advertisers"], "pages": {"forAdvertisers": {}}}`), "/ /sitemap /for_advertisers"; got != want {
		t.Errorf("already listed: %q, want %q", got, want)
	}
}

func TestSitemapPagesFromConfig_DefaultsWhenUnset(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{"displayName": "BodyTheory"}`, httptest.NewRequest(http.MethodGet, "/sitemap_pages.xml", nil))
	got := sitemapPagesFromConfig(middlewares.GetClientConfig(req.Context()))
	if strings.Join(got, " ") != strings.Join(defaultSitemapPages, " ") {
		t.Fatalf("pages = %v, want %v", got, defaultSitemapPages)
	}
	if got := sitemapPagesFromConfig(nil); strings.Join(got, " ") != strings.Join(defaultSitemapPages, " ") {
		t.Fatalf("pages(nil) = %v, want %v", got, defaultSitemapPages)
	}
}

func TestLegacySitemapRedirectPath(t *testing.T) {
	tests := []struct {
		path   string
		want   string
		wantOK bool
	}{
		{"/sitemap/sitemap_claims-and-coverage.xml", "/sitemap_claims-and-coverage.xml", true},
		{"/sitemap/sitemap_budgeting.xml", "/sitemap_budgeting.xml", true},
		{"/sitemap/sitemap_wine-101.xml", "/sitemap_wine-101.xml", true},
		// Only plain lowercase slugs redirect; junk 404s.
		{"/sitemap/sitemap_Budgeting.xml", "", false},
		{"/sitemap/sitemap_.xml", "", false},
		{"/sitemap/sitemap_a--b.xml", "", false},
		{"/sitemap/sitemap_a_b.xml", "", false},
		{"/sitemap/sitemap_a/b.xml", "", false},
		{"/sitemap/sitemap_budgeting.xml/", "", false},
		{"/sitemap//sitemap_budgeting.xml", "", false},
		{"//sitemap/sitemap_budgeting.xml", "", false},
		{`/sitemap/sitemap_\evil.xml`, "", false},
		{"/sitemap/sitemap_budgeting.XML", "", false},
		{"/sitemap_budgeting.xml", "", false},
	}
	for _, tt := range tests {
		got, ok := legacySitemapRedirectPath(tt.path)
		if got != tt.want || ok != tt.wantOK {
			t.Errorf("legacySitemapRedirectPath(%q) = (%q, %v), want (%q, %v)", tt.path, got, ok, tt.want, tt.wantOK)
		}
	}
}

func TestServeLegacySitemapRedirect(t *testing.T) {
	rec := httptest.NewRecorder()
	if !serveLegacySitemapRedirect(rec, httptest.NewRequest(http.MethodGet, "/sitemap/sitemap_claims-and-coverage.xml", 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"), "/sitemap_claims-and-coverage.xml"; 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")
	}

	// Raw request targets, as sent on the wire (%5C = "\", %09 = tab).
	for _, path := range []string{"/sitemap/sitemap_%5Cevil.xml", "/sitemap/sitemap_%09.xml", "//sitemap/sitemap_a.xml", "/sitemap/sitemap_a%2Fb.xml", "/sitemap/sitemap_A.xml"} {
		rec := httptest.NewRecorder()
		if serveLegacySitemapRedirect(rec, httptest.NewRequest(http.MethodGet, path, nil)) {
			t.Fatalf("%s: redirected to %q, want no redirect", path, rec.Header().Get("Location"))
		}
	}
}

func TestBuildSitemapArticlePathWithoutSubcategory(t *testing.T) {
	article := map[string]interface{}{"id": "1780966", "slug_title": "hair care routine", "category": "Beauty", "sub_category": "Hair"}
	if got := buildSitemapArticlePath(article, "Beauty", articleURLOptions{WithSubcategory: true}); got != "/beauty/hair/1780966-hair-care-routine" {
		t.Errorf("with subcategory: %q", got)
	}
	if got := buildSitemapArticlePath(article, "Beauty", articleURLOptions{}); got != "/beauty/1780966-hair-care-routine" {
		t.Errorf("without subcategory: %q", got)
	}
}

func TestBuildSitemapArticlePathSlugFromTitle(t *testing.T) {
	article := map[string]interface{}{"id": "8929", "slug_title": "", "meta_title": "Hair Caring Tips for Colored Hair", "title": "Care Your Colored Hair!", "category": "Fashion"}
	if got := buildSitemapArticlePath(article, "Fashion", articleURLOptions{WithSubcategory: true}); got != "/fashion/8929-hair-caring-tips-for-colored-hair" {
		t.Errorf("default (meta title): %q", got)
	}
	if got := buildSitemapArticlePath(article, "Fashion", articleURLOptions{SlugFromTitle: true}); got != "/fashion/8929-care-your-colored-hair" {
		t.Errorf("slug from title: %q", got)
	}
	amp := map[string]interface{}{"id": "29085", "slug_title": "LGBTQ Support & Inclusive Resources", "category": "News"}
	if got := buildSitemapArticlePath(amp, "News", articleURLOptions{}); got != "/news/29085-lgbtq-support-inclusive-resources" {
		t.Errorf("& dropped (default): %q", got)
	}
	if got := buildSitemapArticlePath(amp, "News", articleURLOptions{AmpersandAsAnd: true}); got != "/news/29085-lgbtq-support-and-inclusive-resources" {
		t.Errorf("& as and: %q", got)
	}
}
