package routes

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

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

// Same inputs/outputs as oos-singlecube's legacyArticleSlug test (fists.com's live URLs).
func TestLegacyArticleSlug(t *testing.T) {
	cases := map[string]string{
		"Henry Armstrong: Major Boxing Record & World Title Reigns": "henry-armstrong-major-boxing-record--world-title-reigns",
		"Tips for First-Time Boxers":                                "tips-for-firsttime-boxers",
		"Trailing Space ":                                           "trailing-space-",
		"":                                                          "",
	}
	for in, want := range cases {
		if got := legacyArticleSlug(in); got != want {
			t.Errorf("legacyArticleSlug(%q) = %q, want %q", in, got, want)
		}
	}
	if got := buildLegacyArticleDetailPath("Blog", "", "1780779", "Record & Titles"); got != "/blog/1780779-record--titles" {
		t.Errorf("buildLegacyArticleDetailPath = %q", got)
	}
}

func TestForArticleURLTitleOnlyAndLegacySlug(t *testing.T) {
	meta := articlePageMeta{
		Category:     "Health",
		SlugTitle:    "Healthy Habits",
		CMSSlugTitle: "Healthy Habits",
		CMSTitle:     "Boost Your Energy & Mood",
	}
	cases := []struct {
		opts articleURLOptions
		want string
	}{
		// slug_title wins by default, and with SlugFromTitle (which only replaces the meta title).
		{articleURLOptions{}, "/health/1756517-healthy-habits"},
		{articleURLOptions{SlugFromTitle: true}, "/health/1756517-healthy-habits"},
		// lifeinterest: the title, always, with "&" spelled out.
		{articleURLOptions{TitleOnly: true, AmpersandAsAnd: true}, "/health/1756517-boost-your-energy-and-mood"},
		// fists: the title, always, by the legacy rule.
		{articleURLOptions{TitleOnly: true, LegacySlug: true}, "/health/1756517-boost-your-energy--mood"},
	}
	for _, c := range cases {
		if got := canonicalArticlePath(forArticleURL(meta, c.opts), "1756517"); got != c.want {
			t.Errorf("%+v: %q, want %q", c.opts, got, c.want)
		}
	}

	shared := map[string]interface{}{"articleSlugTitleOnly": true, "articleSlugLegacy": true}
	opts := articleURLOptionsFromConfig(&middlewares.ClientConfig{ViperConfig: viper.New(), Raw: map[string]interface{}{"shared": shared}})
	if !opts.TitleOnly || !opts.LegacySlug || !opts.WithSubcategory {
		t.Errorf("articleURLOptionsFromConfig = %+v", opts)
	}
}

// The sitemap builds the same URLs as the article page's canonical, untrimmed
// title included (legacyArticleSlug turns a trailing space into a hyphen).
func TestBuildSitemapArticlePathTitleOnlyAndLegacy(t *testing.T) {
	article := map[string]interface{}{"id": "7", "category": "Blog", "slug_title": "Short", "meta_title": "Meta", "title": "Who Is Ali? Record "}
	cases := []struct {
		opts articleURLOptions
		want string
	}{
		{articleURLOptions{WithSubcategory: true}, "/blog/7-short"},
		{articleURLOptions{WithSubcategory: true, TitleOnly: true}, "/blog/7-who-is-ali-record"},
		{articleURLOptions{WithSubcategory: true, TitleOnly: true, LegacySlug: true}, "/blog/7-who-is-ali-record-"},
	}
	for _, c := range cases {
		if got := buildSitemapArticlePath(article, "", c.opts); got != c.want {
			t.Errorf("%+v: %q, want %q", c.opts, got, c.want)
		}
	}
}

func TestLegacyURLRules(t *testing.T) {
	rules := parseLegacyURLRules(map[string]interface{}{
		"redirects": []interface{}{
			map[string]interface{}{"from": "^/site_map/?$", "to": "/sitemap"},
			map[string]interface{}{"from": "^/search/(\\d+)/?$", "to": "/search?page=$1"},
			map[string]interface{}{"from": "^/search/([^/]+)/?$", "to": "/search?term=${1}"},
			map[string]interface{}{"from": "^/search/?$", "to": "/search"},
			map[string]interface{}{"from": "^/+product_details/([^/]+)/([^/]+)/?$", "to": "/shop/product-details/$1/$2"},
			map[string]interface{}{"from": "([", "to": "/broken"},
		},
		"gone": []interface{}{"^/category(/.*)?$", "^/search/?\\?(.*&)?loc=", "(["},
	})
	if len(rules.Redirects) != 5 || len(rules.Gone) != 2 {
		t.Fatalf("invalid rules not skipped: %d redirects, %d gone", len(rules.Redirects), len(rules.Gone))
	}

	redirects := []struct{ path, query, wantPath, wantQuery string }{
		{"/site_map/", "", "/sitemap", ""},
		{"/site_map", "utm=x", "/sitemap", "utm=x"},
		// bridalfusion: page and the legacy search param in one hop.
		{"/search/3", "search=rings", "/search", "page=3&term=rings"},
		{"/search/", "search=rings", "/search", "term=rings"},
		// The older ?keyword= is renamed too (one hop to the live sites' ?term=).
		{"/search/", "keyword=rings", "/search", "term=rings"},
		{"//product_details/AB12/red-dress", "", "/shop/product-details/AB12/red-dress", ""},
		// Groups are query-escaped in a "to" query (paths come decoded: /search/a%26b%23c).
		{"/search/canelo alvarez", "", "/search", "term=canelo+alvarez"},
		{"/search/a&b#c", "", "/search", "term=a%26b%23c"},
		// A key the "to" query sets replaces the request's own.
		{"/search/3", "page=5&search=rings", "/search", "page=3&term=rings"},
	}
	for _, c := range redirects {
		path, query, ok := rules.redirectTarget(c.path, c.query)
		if !ok || path != c.wantPath || query != c.wantQuery {
			t.Errorf("redirectTarget(%q, %q) = %q, %q, %v; want %q, %q", c.path, c.query, path, query, ok, c.wantPath, c.wantQuery)
		}
	}
	// A rule that would send a URL to itself is no redirect.
	if path, query, ok := rules.redirectTarget("/search", "term=rings"); ok {
		t.Errorf("/search?term= redirected to %q?%q", path, query)
	}

	for _, c := range []struct {
		path, query string
		want        bool
	}{
		{"/category", "", true},
		{"/category/arts-and-entertainment", "", true},
		{"/search/", "s=car+wash&loc=Ashburn", true},
		{"/search", "term=x", false},
		{"/categories/car-insurance", "", false},
	} {
		if got := rules.isGone(c.path, c.query); got != c.want {
			t.Errorf("isGone(%q, %q) = %v, want %v", c.path, c.query, got, c.want)
		}
	}
}

func TestLegacyCategoryPagePath(t *testing.T) {
	cases := []struct {
		path, query                  string
		wantCat, wantPath, wantQuery string
		wantOK                       bool
	}{
		{"/health/2", "", "health", "/health", "page=2", true},
		{"/articles/37/", "", "articles", "/articles", "page=37", true},
		{"/health/1", "utm=x", "health", "/health", "utm=x", true},
		{"/health/3", "utm=x", "health", "/health", "utm=x&page=3", true},
		// Article IDs (above maxLegacyCategoryPage), page 0, existing ?page, other shapes: no.
		{"/sports/5677", "", "", "", "", false},
		{"/health/0", "", "", "", "", false},
		{"/health/2", "page=4", "", "", "", false},
		{"/health/2-slug", "", "", "", "", false},
		{"/a/b/2", "", "", "", "", false},
	}
	for _, c := range cases {
		cat, path, query, ok := legacyCategoryPagePath(c.path, c.query)
		if cat != c.wantCat || path != c.wantPath || query != c.wantQuery || ok != c.wantOK {
			t.Errorf("legacyCategoryPagePath(%q, %q) = %q %q %q %v", c.path, c.query, cat, path, query, ok)
		}
	}
}

func TestLegacyURLMiddleware(t *testing.T) {
	orig := cmsService
	cmsService = nil // the CMS can't tell, so a legacy page URL redirects
	t.Cleanup(func() { cmsService = orig })

	raw := map[string]interface{}{
		"template": "magazine",
		"legacyUrls": map[string]interface{}{
			"categoryPagination": true,
			"redirects":          []interface{}{map[string]interface{}{"from": "^/site_map/?$", "to": "/sitemap"}},
			"gone":               []interface{}{"^/category(/.*)?$"},
		},
	}
	withRules := &middlewares.ClientConfig{ViperConfig: viper.New(), Raw: raw}
	without := &middlewares.ClientConfig{ViperConfig: viper.New(), Raw: map[string]interface{}{"template": "magazine"}}
	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := legacyURLMiddleware(next, pageTemplatesFrom("../web/templates"))
	serve := func(config *middlewares.ClientConfig, method, target string) *httptest.ResponseRecorder {
		req := httptest.NewRequest(method, "https://insuranceandleisure.com"+target, nil)
		req = req.WithContext(context.WithValue(req.Context(), middlewares.ClientConfigKey, config))
		rec := httptest.NewRecorder()
		handler.ServeHTTP(rec, req)
		return rec
	}

	if rec := serve(withRules, http.MethodGet, "/category/arts"); rec.Code != http.StatusGone {
		t.Errorf("gone: %d, want 410", rec.Code)
	}
	if rec := serve(withRules, http.MethodGet, "/site_map?x=1"); rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/sitemap?x=1" ||
		rec.Header().Get("Cache-Control") != seoRedirectCacheControl {
		t.Errorf("redirect: %d %q %q", rec.Code, rec.Header().Get("Location"), rec.Header().Get("Cache-Control"))
	}
	if rec := serve(withRules, http.MethodGet, "/health/2"); rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/health?page=2" {
		t.Errorf("pagination: %d %q", rec.Code, rec.Header().Get("Location"))
	}
	for _, c := range []struct {
		config *middlewares.ClientConfig
		method string
		path   string
	}{
		{withRules, http.MethodGet, "/health"},
		{withRules, http.MethodPost, "/category/arts"},
		{without, http.MethodGet, "/category/arts"},
		{without, http.MethodGet, "/health/2"},
	} {
		if rec := serve(c.config, c.method, c.path); rec.Code != http.StatusTeapot {
			t.Errorf("%s %s: %d, want it passed on", c.method, c.path, rec.Code)
		}
	}
}

func TestLeavesSite(t *testing.T) {
	for path, want := range map[string]bool{
		"/":                   false,
		"/sitemap":            false,
		"/a//b":               false,
		"/%41bout":            false,
		"/100%":               false, // not valid escaping: as it is
		"//evil.com":          true,
		"///evil.com":         true,
		"/\\evil.com":         true,
		"/\t/evil.com":        true,
		"/\n/evil.com":        true,
		"/%2Fevil.com":        true,
		"/%2fevil.com":        true,
		"/%5Cevil.com":        true,
		"/%252F%252Fevil.com": true,
		"/%09/evil.com":       true,
		"/%25252525252Fx.com": true, // still encoded after every round
	} {
		if got := leavesSite(path); got != want {
			t.Errorf("leavesSite(%q) = %v, want %v", path, got, want)
		}
	}
}

// A legacy redirect whose group starts with "/" must never send the browser
// to another host (qualifiedlawyers' and localpages' rules did): 404 instead.
func TestLegacyURLMiddleware_NoOpenRedirect(t *testing.T) {
	orig := cmsService
	cmsService = nil
	t.Cleanup(func() { cmsService = orig })
	next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })
	handler := legacyURLMiddleware(next, pageTemplatesFrom("../web/templates"))
	for _, template := range []string{"directory", "magazine"} {
		config := &middlewares.ClientConfig{ViperConfig: viper.New(), Raw: map[string]interface{}{
			"template": template,
			"legacyUrls": map[string]interface{}{"redirects": []interface{}{
				map[string]interface{}{"from": "^/index\\.php/(.+)$", "to": "/$1"},
				map[string]interface{}{"from": "^/blog/(.*[^/])/?$", "to": "/${1}"},
			}},
		}}
		for _, tt := range []struct {
			target   string
			status   int
			location string
		}{
			{"/index.php/about", http.StatusMovedPermanently, "/about"},
			{"/index.php//evil.com", http.StatusNotFound, ""},
			{"/index.php///evil.com/x", http.StatusNotFound, ""},
			{"/index.php/%2F%2Fevil.com", http.StatusNotFound, ""},
			{"/index.php/%5Cevil.com", http.StatusNotFound, ""},
			{"/index.php/%252F%252Fevil.com", http.StatusNotFound, ""},
			{"/blog//evil.com/x", http.StatusNotFound, ""},
		} {
			req := httptest.NewRequest(http.MethodGet, "https://qualifiedlawyers.com"+tt.target, nil)
			req = req.WithContext(context.WithValue(req.Context(), middlewares.ClientConfigKey, config))
			rec := httptest.NewRecorder()
			handler.ServeHTTP(rec, req)
			if rec.Code != tt.status || rec.Header().Get("Location") != tt.location {
				t.Errorf("%s %s: %d %q, want %d %q", template, tt.target, rec.Code, rec.Header().Get("Location"), tt.status, tt.location)
			}
		}
	}
}

func TestExtraPageAt(t *testing.T) {
	raw := map[string]interface{}{"pages": map[string]interface{}{
		"faq":     map[string]interface{}{"path": "/faq", "content": map[string]interface{}{"title": "FAQ"}},
		"empty":   map[string]interface{}{"path": "/empty"},
		"aboutUs": map[string]interface{}{"content": map[string]interface{}{"title": "About"}},
	}}
	raw["pages"].(map[string]interface{})["bad"] = map[string]interface{}{"path": "//evil.example", "content": map[string]interface{}{"title": "x"}}
	for path, want := range map[string]string{"/faq": "faq", "/empty": "", "/about": "", "/faq/": "", "//evil.example": ""} {
		if got := extraPageAt(raw, path); got != want {
			t.Errorf("extraPageAt(%q) = %q, want %q", path, got, want)
		}
	}
}

func TestArticleBelongsToSite(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Query().Get("action") {
		case "getcategories":
			fmt.Fprint(w, `{"data":{"a.com":[{"cat_id":"1","cat_name":"Health & Fitness","subcategories":[{"id":"9","name":"Yoga"}]}],"b.com":[{"cat_id":"2","cat_name":"Bars & Clubs"}]}}`)
		case "getcategoryarticles":
			if r.URL.Query().Get("cat_id") == "1" {
				// Article 7 is a.com's, though the CMS files it under an old category name.
				fmt.Fprint(w, `{"data":[{"id":"7","title":"Old"}]}`)
				return
			}
			fmt.Fprint(w, `{"data":[]}`)
		}
	}))
	t.Cleanup(server.Close)
	orig := cmsService
	cmsService = cms.NewService(server.URL, "test-key", 0)
	t.Cleanup(func() { cmsService = orig })

	cases := []struct {
		host, category, id string
		want               bool
	}{
		{"a.com", "Health & Fitness", "1", true},
		{"a.com", "Yoga", "2", true},
		// A category no site has yet (new since the categories were cached): served.
		{"a.com", "Brand New", "99", true},
		// Filed under another site's category name but listed by a.com: a.com's.
		{"a.com", "Bars & Clubs", "7", true},
		// porschemotorcar.com/articles/37 used to serve b.com's article.
		{"a.com", "Bars & Clubs", "37", false},
		// A site the CMS doesn't list: it can't tell, so the article is served.
		{"c.com", "Bars & Clubs", "37", true},
	}
	for _, c := range cases {
		req := httptest.NewRequest(http.MethodGet, "https://"+c.host+"/x/"+c.id, nil)
		if got := articleBelongsToSite(req, c.category, c.id); got != c.want {
			t.Errorf("%s %q %s: %v, want %v", c.host, c.category, c.id, got, c.want)
		}
	}
}

// A category name several sites have ("Articles" on 84 sites) doesn't make an
// article the site's: its own listings must include it.
func TestArticleBelongsToSite_SharedCategoryName(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch r.URL.Query().Get("action") {
		case "getcategories":
			fmt.Fprint(w, `{"data":{"x.com":[{"cat_id":"3","cat_name":"Articles"},{"cat_id":"5","cat_name":"Schools"}],"y.com":[{"cat_id":"4","cat_name":"Articles"}]}}`)
		case "getcategoryarticles":
			switch r.URL.Query().Get("cat_id") {
			case "3":
				fmt.Fprint(w, `{"data":[{"id":"20","title":"Learning"}]}`)
			case "4":
				fmt.Fprint(w, `{"data":[{"id":"21","title":"Crypto"}]}`)
			default:
				fmt.Fprint(w, `{"data":[]}`)
			}
		}
	}))
	t.Cleanup(server.Close)
	orig := cmsService
	cmsService = cms.NewService(server.URL, "test-key", 0)
	t.Cleanup(func() { cmsService = orig })
	t.Cleanup(func() { siteArticleIDCache.Delete("x.com"); siteArticleIDCache.Delete("y.com") })

	cases := []struct {
		host, category, id string
		want               bool
	}{
		{"x.com", "Articles", "20", true},
		// educationalcraft.com/articles/1781336 served stockprices.com's article.
		{"x.com", "Articles", "21", false},
		{"y.com", "Articles", "21", true},
		// A name only x.com has needs no listing.
		{"x.com", "Schools", "99", true},
	}
	for _, c := range cases {
		req := httptest.NewRequest(http.MethodGet, "https://"+c.host+"/x/"+c.id, nil)
		if got := articleBelongsToSite(req, c.category, c.id); got != c.want {
			t.Errorf("%s %q %s: %v, want %v", c.host, c.category, c.id, got, c.want)
		}
	}
}
