package routes

import (
	"context"
	"go/ast"
	"go/parser"
	"go/token"
	"net/http"
	"net/http/httptest"
	"strconv"
	"strings"
	"testing"

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

func TestCmsArticleMissing(t *testing.T) {
	cases := map[string]bool{
		`{"data": false}`:           true,
		`{"data":false}`:            true,
		`{"data": {"id": "1"}}`:     false,
		`{"data": null}`:            false,
		`{}`:                        false,
		`not json`:                  false,
		`{"data": "false"}`:         false,
		`{"data": false, "x": 1}`:   true,
		`{"error": "rate limited"}`: false,
	}
	for body, want := range cases {
		if got := cmsArticleMissing([]byte(body)); got != want {
			t.Errorf("cmsArticleMissing(%s) = %v, want %v", body, got, want)
		}
	}
}

// An article the CMS doesn't have is a 301 to its listing (see
// TestArticleDetailHandler_DeletedArticleRedirect); a failed CMS request is
// not, and keeps the page indexable; a non-numeric ID is a 404 (noindex, no
// canonical or Article data).
func TestArticleDetailHandler_MissingVsFailedArticle(t *testing.T) {
	var requestedIDs []string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := r.URL.Query().Get("id")
		requestedIDs = append(requestedIDs, id)
		if id == "500" {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		if !isNumericID(id) {
			// What the CMS answers for an ID that isn't a number.
			w.Write([]byte(`{"data":[],"error":"Please pass article id"}`))
			return
		}
		w.Write([]byte(`{"data": false}`))
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()

	v := viper.New()
	v.Set("displayName", "411atkins.com")
	config := &middlewares.ClientConfig{ViperConfig: v, Raw: map[string]interface{}{"template": "editorial"}}
	handler := articleDetailHandler(pageTemplatesFrom("../web/templates"))
	serve := func(id string) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodGet, "https://411atkins.com/claims/"+id+"-some-title", nil)
		ctx := context.WithValue(req.Context(), middlewares.ClientConfigKey, config)
		ctx = context.WithValue(ctx, httprouter.ParamsKey, httprouter.Params{
			{Key: "category", Value: "claims"},
			{Key: "slug", Value: id + "-some-title"},
		})
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, req.WithContext(ctx))
		return rec
	}

	rec := serve("404")
	if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/claims" {
		t.Fatalf("missing article: %d %q, want 301 /claims", rec.Code, rec.Header().Get("Location"))
	}

	rec = serve("500")
	html := rec.Body.String()
	if rec.Code != http.StatusOK {
		t.Fatalf("failed CMS request: status = %d, want 200", rec.Code)
	}
	if got := rec.Header().Get("X-Robots-Tag"); got != "index, follow" {
		t.Errorf("failed CMS request: X-Robots-Tag = %q, want index, follow", got)
	}
	if !strings.Contains(html, `rel="canonical"`) {
		t.Error("failed CMS request: canonical missing")
	}

	// "/claims/1760806x-some-title": not an article ID, so a 404 like a missing
	// article, without asking the CMS.
	requestedIDs = nil
	rec = serve("1760806x")
	html = rec.Body.String()
	if rec.Code != http.StatusNotFound {
		t.Fatalf("non-numeric ID: status = %d, want 404", rec.Code)
	}
	if got := rec.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" {
		t.Errorf("non-numeric ID: X-Robots-Tag = %q, want noindex, nofollow", got)
	}
	if !strings.Contains(html, "<title>Page not found - 411atkins.com</title>") {
		t.Error("non-numeric ID: no not-found title")
	}
	for _, unwanted := range []string{`rel="canonical"`, "oos-article-schema"} {
		if strings.Contains(html, unwanted) {
			t.Errorf("non-numeric ID: page has %q", unwanted)
		}
	}
	if len(requestedIDs) != 0 {
		t.Errorf("non-numeric ID: CMS was asked for %v", requestedIDs)
	}
}

// An article deleted from the CMS 301s to the deepest listing its URL names
// that the site has, else home; another site's article stays a 404.
func TestArticleDetailHandler_DeletedArticleRedirect(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":{"a.com":[{"cat_id":"1","cat_name":"Golf","subcategories":[{"id":"9","name":"Tours"}]}],"b.com":[{"cat_id":"2","cat_name":"Tennis"}]}}`))
		case "getcategoryarticles":
			w.Write([]byte(`{"data":[]}`))
		case "getarticledata":
			if r.URL.Query().Get("id") == "37" {
				// b.com's article.
				w.Write([]byte(`{"data":{"id":"37","title":"Serve","category":"Tennis"}}`))
				return
			}
			w.Write([]byte(`{"data": false}`))
		}
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()
	// The ownership check caches a.com's listed IDs; don't leave them to other tests.
	defer siteArticleIDCache.Delete("a.com")

	v := viper.New()
	v.Set("displayName", "a.com")
	config := &middlewares.ClientConfig{ViperConfig: v, Raw: map[string]interface{}{"template": "editorial"}}
	handler := articleDetailHandler(pageTemplatesFrom("../web/templates"))
	serve := func(path string, params httprouter.Params) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodGet, "https://a.com"+path, nil)
		ctx := context.WithValue(req.Context(), middlewares.ClientConfigKey, config)
		ctx = context.WithValue(ctx, httprouter.ParamsKey, params)
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, req.WithContext(ctx))
		return rec
	}
	cat := func(category, slug string) httprouter.Params {
		return httprouter.Params{{Key: "category", Value: category}, {Key: "slug", Value: slug}}
	}
	sub := func(category, subcategory, slug string) httprouter.Params {
		return httprouter.Params{{Key: "category", Value: category}, {Key: "subcategory", Value: subcategory}, {Key: "slug", Value: slug}}
	}

	for _, c := range []struct {
		path   string
		params httprouter.Params
		want   string
	}{
		{"/golf/5677-tiger-woods", cat("golf", "5677-tiger-woods"), "/golf"},
		// A subcategory name in the category position, as category pages allow.
		{"/tours/5677-tiger-woods", cat("tours", "5677-tiger-woods"), "/tours"},
		{"/golf/tours/5677-tiger-woods", sub("golf", "tours", "5677-tiger-woods"), "/golf/tours"},
		{"/golf/majors/5677-tiger-woods", sub("golf", "majors", "5677-tiger-woods"), "/golf"},
		// Another site's category, and one no site has.
		{"/tennis/5677-tiger-woods", cat("tennis", "5677-tiger-woods"), "/"},
		{"/boxing/tours/5677-tiger-woods", sub("boxing", "tours", "5677-tiger-woods"), "/"},
		{"/article/5677-tiger-woods", httprouter.Params{{Key: "slug", Value: "5677-tiger-woods"}}, "/"},
		{"/golf/5677-tiger-woods?utm_source=x", cat("golf", "5677-tiger-woods"), "/golf?utm_source=x"},
	} {
		rec := serve(c.path, c.params)
		if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != c.want {
			t.Errorf("%s: %d %q, want 301 %q", c.path, rec.Code, rec.Header().Get("Location"), c.want)
		}
		if got := rec.Header().Get("Cache-Control"); got != seoRedirectCacheControl {
			t.Errorf("%s: Cache-Control = %q, want %q", c.path, got, seoRedirectCacheControl)
		}
	}

	if rec := serve("/tennis/37-serve", cat("tennis", "37-serve")); rec.Code != http.StatusNotFound {
		t.Errorf("another site's article: status = %d, want 404", rec.Code)
	}
}

// An article of a category whose page shows it in full (pages.category.layouts
// "article") 301s from any of its URLs to that page; the category's sitemap
// lists only the page. Other articles keep their own URLs.
func TestCategoryShowsArticle_RedirectAndSitemap(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":{"a.com":[{"cat_id":"1","cat_name":"Schedule"},{"cat_id":"2","cat_name":"History"}]}}`))
		case "getcategoryarticles":
			if r.URL.Query().Get("cat_id") == "1" {
				w.Write([]byte(`{"data":[{"id":40,"title":"Boxing Schedule 2026","category":"Schedule","timestamp":1794827502}]}`))
				return
			}
			w.Write([]byte(`{"data":[{"id":41,"title":"Ali","category":"History","timestamp":1714658709}]}`))
		case "getarticledata":
			if r.URL.Query().Get("id") == "41" {
				w.Write([]byte(`{"data":{"id":41,"title":"Ali","category":"History"}}`))
				return
			}
			w.Write([]byte(`{"data":{"id":40,"title":"Boxing Schedule 2026","category":"Schedule"}}`))
		}
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()
	defer siteArticleIDCache.Delete("a.com")

	v := viper.New()
	v.Set("displayName", "a.com")
	config := &middlewares.ClientConfig{ViperConfig: v, Raw: map[string]interface{}{
		"template": "magazine",
		"pages":    map[string]interface{}{"category": map[string]interface{}{"layouts": map[string]interface{}{"schedule": "article"}}},
	}}
	withConfig := func(req *http.Request, params httprouter.Params) *http.Request {
		ctx := context.WithValue(req.Context(), middlewares.ClientConfigKey, config)
		return req.WithContext(context.WithValue(ctx, httprouter.ParamsKey, params))
	}
	handler := articleDetailHandler(pageTemplatesFrom("../web/templates"))
	cat := func(category, slug string) httprouter.Params {
		return httprouter.Params{{Key: "category", Value: category}, {Key: "slug", Value: slug}}
	}

	for _, c := range []struct {
		path   string
		params httprouter.Params
		want   string
	}{
		{"/schedule/40-boxing-schedule-2026", cat("schedule", "40-boxing-schedule-2026"), "/schedule"},
		{"/schedule/40-old-slug?utm_source=x", cat("schedule", "40-old-slug"), "/schedule?utm_source=x"},
		{"/article/40-boxing-schedule-2026", httprouter.Params{{Key: "slug", Value: "40-boxing-schedule-2026"}}, "/schedule"},
		// Any other category's article goes to its own canonical URL.
		{"/history/41-old-slug", cat("history", "41-old-slug"), "/history/41-ali"},
	} {
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, withConfig(httptest.NewRequest(http.MethodGet, "https://a.com"+c.path, nil), c.params))
		if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != c.want {
			t.Errorf("%s: %d %q, want 301 %q", c.path, rec.Code, rec.Header().Get("Location"), c.want)
		}
	}

	for slug, want := range map[string][]string{
		"schedule": {"<loc>https://a.com/schedule</loc>", "<lastmod>2026-11-16</lastmod>"},
		"history":  {"<loc>https://a.com/history</loc>", "<loc>https://a.com/history/41-ali</loc>"},
	} {
		rec := httptest.NewRecorder()
		SitemapCategoryHandler(slug).ServeHTTP(rec, withConfig(httptest.NewRequest(http.MethodGet, "https://a.com/sitemap_"+slug+".xml", nil), nil))
		body := rec.Body.String()
		for _, part := range want {
			if !strings.Contains(body, part) {
				t.Errorf("sitemap_%s.xml: missing %s in %s", slug, part, body)
			}
		}
		if slug == "schedule" && strings.Contains(body, "/schedule/40-") {
			t.Errorf("sitemap_schedule.xml lists the article's own URL: %s", body)
		}
	}
}

// nonArticleRoutePrefixes must follow main.go's routes: every route other than
// the article ones is no article URL for articleRouteParams (with any values
// in its params), and every prefix is still a route's.
func TestNonArticleRoutePrefixes_MatchMainRoutes(t *testing.T) {
	file, err := parser.ParseFile(token.NewFileSet(), "../main.go", nil, 0)
	if err != nil {
		t.Fatal(err)
	}
	firstSegments := map[string]bool{}
	routes := 0
	ast.Inspect(file, func(n ast.Node) bool {
		call, ok := n.(*ast.CallExpr)
		if !ok || len(call.Args) != 3 {
			return true
		}
		if sel, ok := call.Fun.(*ast.SelectorExpr); !ok || sel.Sel.Name != "Handler" {
			return true
		}
		lit, ok := call.Args[1].(*ast.BasicLit)
		if !ok || lit.Kind != token.STRING {
			return true
		}
		path, err := strconv.Unquote(lit.Value)
		if err != nil {
			t.Fatal(err)
		}
		routes++
		handler := ""
		if h, ok := call.Args[2].(*ast.CallExpr); ok {
			if sel, ok := h.Fun.(*ast.SelectorExpr); ok {
				handler = sel.Sel.Name
			}
		}
		first, _, _ := strings.Cut(strings.TrimPrefix(path, "/"), "/")
		firstSegments[first] = true
		if handler == "ArticleDetailHandler" {
			return true
		}
		// A param can be anything, an article slug too.
		segments := strings.Split(path, "/")
		for i, segment := range segments {
			if strings.HasPrefix(segment, ":") || strings.HasPrefix(segment, "*") {
				segments[i] = "77-x"
			}
		}
		if params, ok := articleRouteParams(strings.Join(segments, "/")); ok {
			t.Errorf("main.go route %s (%s) reads as an article URL %v: add %q to nonArticleRoutePrefixes", path, handler, params, first)
		}
		return true
	})
	if routes < 20 {
		t.Fatalf("found %d routes in main.go; is it still registering them with router.Handler?", routes)
	}
	for prefix := range nonArticleRoutePrefixes {
		if !firstSegments[prefix] {
			t.Errorf("nonArticleRoutePrefixes has %q, which no main.go route starts with", prefix)
		}
	}
}
