package routes

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

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

func TestPageTitleFromName(t *testing.T) {
	cases := map[string]string{
		"terms":          "Terms and Conditions",
		"privacyPolicy":  "Privacy Policy",
		"aboutUs":        "About Us",
		"contactUs":      "Contact Us",
		"sitemap":        "Sitemap",
		"forAdvertisers": "For Advertisers",
		"notFound":       "Page Not Found",
	}
	for in, want := range cases {
		if got := pageTitleFromName(in); got != want {
			t.Errorf("pageTitleFromName(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestHasPageContent(t *testing.T) {
	raw := map[string]interface{}{
		"pages": map[string]interface{}{
			"forAdvertisers": map[string]interface{}{"content": map[string]interface{}{"title": "For Advertisers"}},
			"aboutUs":        map[string]interface{}{"rails": []interface{}{}},
		},
	}
	cases := []struct {
		raw  map[string]interface{}
		page string
		want bool
	}{
		{raw, "forAdvertisers", true},
		{raw, "aboutUs", false}, // page without content
		{raw, "terms", false},   // page not in config
		{map[string]interface{}{"pages": "nope"}, "forAdvertisers", false},
		{nil, "forAdvertisers", false}, // no raw config (e.g. classic sites in tests)
	}
	for _, c := range cases {
		if got := hasPageContent(c.raw, c.page); got != c.want {
			t.Errorf("hasPageContent(%v, %q) = %v, want %v", c.raw, c.page, got, c.want)
		}
	}
}

func TestServesConfiguredPage(t *testing.T) {
	contact := map[string]interface{}{"contactUs": map[string]interface{}{"content": map[string]interface{}{"title": "Contact Us"}}}
	editorialWithContact := map[string]interface{}{"template": "editorial", "pages": contact}
	editorialWithout := map[string]interface{}{"template": "editorial", "pages": map[string]interface{}{}}
	magazineWithContact := map[string]interface{}{"template": "magazine", "pages": contact}
	magazineWithout := map[string]interface{}{"template": "magazine", "pages": map[string]interface{}{}}
	classic := map[string]interface{}{"displayName": "Point Wines"} // pages live in the bundled frontend config

	cases := []struct {
		name             string
		raw              map[string]interface{}
		page             string
		siteTemplateOnly bool
		want             bool
	}{
		{"editorial site with the page", editorialWithContact, "contactUs", true, true},
		{"editorial site without the page", editorialWithout, "contactUs", true, false},
		{"magazine site with the page", magazineWithContact, "contactUs", true, true},
		{"magazine site without the page", magazineWithout, "contactUs", true, false},
		{"classic site keeps site-template-only pages", classic, "contactUs", true, true},
		{"classic site without a config-only page", classic, "forAdvertisers", false, false},
		{"no raw config", nil, "forAdvertisers", false, false},
	}
	for _, c := range cases {
		if got := servesConfiguredPage(c.raw, c.page, c.siteTemplateOnly); got != c.want {
			t.Errorf("%s: servesConfiguredPage = %v, want %v", c.name, got, c.want)
		}
	}
}

func TestServeStaticPageShellNotFound(t *testing.T) {
	v := viper.New()
	v.Set("displayName", "411atkins.com")
	config := &middlewares.ClientConfig{ViperConfig: v, Raw: map[string]interface{}{"template": "editorial"}}
	tpl := pageTemplatesFrom("../web/templates")
	serve := func(path, pageName string) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodGet, "https://411atkins.com"+path, nil)
		req = req.WithContext(context.WithValue(req.Context(), middlewares.ClientConfigKey, config))
		rec := httptest.NewRecorder()
		serveStaticPageShell(rec, req, tpl, pageName)
		return rec
	}

	rec := serve("/contact", notFoundPageName)
	html := rec.Body.String()
	if rec.Code != http.StatusNotFound {
		t.Fatalf("status = %d, want 404", rec.Code)
	}
	if got := rec.Header().Get("X-Robots-Tag"); !strings.Contains(got, "noindex") {
		t.Fatalf("X-Robots-Tag = %q, want noindex", got)
	}
	for _, want := range []string{"<title>Page not found - 411atkins.com</title>", `name="viewport"`, `<meta name="robots" content="noindex,nofollow" />`} {
		if !strings.Contains(html, want) {
			t.Errorf("not-found shell is missing %q", want)
		}
	}
	for _, unwanted := range []string{`rel="canonical"`, "BreadcrumbList"} {
		if strings.Contains(html, unwanted) {
			t.Errorf("not-found shell has %q", unwanted)
		}
	}

	// Real pages keep their 200 and canonical.
	rec = serve("/about", "aboutUs")
	if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `rel="canonical"`) {
		t.Fatalf("about: status %d, canonical present %v", rec.Code, strings.Contains(rec.Body.String(), `rel="canonical"`))
	}
}

func TestSiteTemplatePageLabel(t *testing.T) {
	editorial := map[string]interface{}{
		"template": "editorial",
		"pages":    map[string]interface{}{"privacyPolicy": map[string]interface{}{"content": map[string]interface{}{"title": "Privacy"}}},
	}
	magazine := map[string]interface{}{
		"template": "magazine",
		"pages":    map[string]interface{}{"privacyPolicy": map[string]interface{}{"content": map[string]interface{}{"title": "Privacy"}}},
	}
	withLabel := map[string]interface{}{
		"template": "editorial",
		"shared":   map[string]interface{}{"labels": map[string]interface{}{"notFoundTitle": "Not here"}},
	}
	cases := []struct {
		name string
		raw  map[string]interface{}
		page string
		want string
	}{
		{"page content title", editorial, "privacyPolicy", "Privacy"},
		{"page without content", editorial, "terms", ""},
		{"not-found default label", editorial, notFoundPageName, "Page not found"},
		{"not-found configured label", withLabel, notFoundPageName, "Not here"},
		{"magazine page content title", magazine, "privacyPolicy", "Privacy"},
		{"magazine not-found default label", magazine, notFoundPageName, "Page not found"},
		{"classic site", map[string]interface{}{}, "privacyPolicy", ""},
		{"unknown template", map[string]interface{}{"template": "no-such-template"}, notFoundPageName, ""},
		{"non-string template", map[string]interface{}{"template": 1}, notFoundPageName, ""},
	}
	for _, c := range cases {
		if got := siteTemplatePageLabel(c.raw, c.page); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}

func TestLegacyInfoPageHandler(t *testing.T) {
	serve := func(target, page string) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodGet, target, nil)
		req = req.WithContext(context.WithValue(req.Context(), httprouter.ParamsKey, httprouter.Params{{Key: "page", Value: page}}))
		rec := httptest.NewRecorder()
		legacyInfoPageHandler(http.NotFoundHandler()).ServeHTTP(rec, req)
		return rec
	}
	for page, want := range map[string]string{"about": "/about", "privacy": "/privacy", "terms": "/terms", "sitemap": "/sitemap", "contact": "/contact"} {
		rec := serve("https://womenwire.com/info/"+page, page)
		if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != want {
			t.Errorf("/info/%s: %d %q, want 301 %q", page, rec.Code, rec.Header().Get("Location"), want)
		}
		if rec.Header().Get("Cache-Control") != seoRedirectCacheControl {
			t.Errorf("/info/%s: Cache-Control = %q", page, rec.Header().Get("Cache-Control"))
		}
	}
	if rec := serve("https://womenwire.com/info/about?x=1", "about"); rec.Header().Get("Location") != "/about?x=1" {
		t.Errorf("query not kept: %q", rec.Header().Get("Location"))
	}
	if rec := serve("https://gaycommunity.com/site/terms", "terms"); rec.Header().Get("Location") != "/terms" {
		t.Errorf("/site/terms: Location = %q", rec.Header().Get("Location"))
	}
	if rec := serve("https://womenwire.com/info/send_contact", "send_contact"); rec.Code != http.StatusNotFound {
		t.Errorf("unknown /info page: status %d, want 404", rec.Code)
	}
}
