package routes

import (
	"encoding/json"
	"html/template"
	"net/http"
	"strings"
	"testing"

	"bitbucket.org/imediabrands/oos-service/middlewares"
)

func TestThemeCSS(t *testing.T) {
	got := string(themeCSS(map[string]interface{}{
		"--color-button-primary": "#e52a6f",
		"--font-family-primary":  "'Poppins', sans-serif",
		"color":                  "red",                      // not a custom property
		"--bad":                  "red; background: url(x)",  // injection attempt
		"--bad2":                 "url(https://evil.test/x)", // url() not allowed
		"--num":                  12,                         // not a string
	}))
	want := "--color-button-primary:#e52a6f;--font-family-primary:'Poppins', sans-serif;"
	if got != want {
		t.Fatalf("themeCSS = %q, want %q", got, want)
	}
}

func TestThemeCSSNotAnObject(t *testing.T) {
	if got := themeCSS("nope"); got != "" {
		t.Fatalf("themeCSS(non-object) = %q, want empty", got)
	}
	if got := themeCSS(nil); got != "" {
		t.Fatalf("themeCSS(nil) = %q, want empty", got)
	}
}

func TestMergeUIOverridesKeepsKeyCase(t *testing.T) {
	raw := map[string]interface{}{
		"template": "editorial",
		"shared":   map[string]interface{}{"navigation": map[string]interface{}{"useApiCategories": false}},
		"pages":    map[string]interface{}{"homepage": map[string]interface{}{}},
		"theme":    map[string]interface{}{"--x": "1"},
		"meta":     "not passed through",
		"ga_id":    "G-1",
		"logo_url": "x",
	}
	out := mergeUIOverrides(template.JS(`{"siteId":"bestfares"}`), raw)

	if !strings.Contains(string(out), `"useApiCategories":false`) {
		t.Fatalf("camelCase key lost: %s", out)
	}
	var m map[string]interface{}
	if err := json.Unmarshal([]byte(out), &m); err != nil {
		t.Fatal(err)
	}
	if m["siteId"] != "bestfares" {
		t.Errorf("existing keys must be kept, got %v", m)
	}
	if m["template"] != "editorial" {
		t.Errorf("template must be passed through, got %v", m["template"])
	}
	if _, ok := m["shared"]; !ok {
		t.Error("shared missing")
	}
	if _, ok := m["pages"]; !ok {
		t.Error("pages missing")
	}
	for _, k := range []string{"theme", "meta", "ga_id", "logo_url"} {
		if _, ok := m[k]; ok {
			t.Errorf("%q must not be passed to the frontend override config", k)
		}
	}
}

func TestMergeUIOverridesBadExistingJSON(t *testing.T) {
	in := template.JS(`not json`)
	if out := mergeUIOverrides(in, map[string]interface{}{"shared": 1}); out != in {
		t.Fatalf("expected input returned unchanged, got %q", out)
	}
}

func TestSanitizeHeadbidAffID(t *testing.T) {
	tests := map[string]string{
		"128141":                  "128141",
		" 128142 ":                "128142",
		"":                        "",
		"abc":                     "",
		"12a":                     "",
		"1\"></script><script>x(": "",
		"1234567890123":           "", // longer than 12 digits
		// Several ids joined by "_", as accoona's live monitor script sends them.
		"16678_127594_127595_127600_127601_127597_126666_127598": "16678_127594_127595_127600_127601_127597_126666_127598",
		"16678_":        "",
		"_16678":        "",
		"16678__127594": "",
		"16678_12a":     "",
	}
	for in, want := range tests {
		if got := sanitizeHeadbidAffID(in); got != want {
			t.Errorf("sanitizeHeadbidAffID(%q) = %q, want %q", in, got, want)
		}
	}
}

func TestSanitizeAdsenseAccount(t *testing.T) {
	for in, want := range map[string]string{
		"sites-2288675768043065":   "sites-2288675768043065",
		" sites-2288675768043065 ": "sites-2288675768043065",
		"":                         "",
		"ca-pub-123":               "ca-pub-123",
		"sites-":                   "",
		`sites-1" /><script>`:      "",
	} {
		if got := sanitizeAdsenseAccount(in); got != want {
			t.Errorf("sanitizeAdsenseAccount(%q) = %q, want %q", in, got, want)
		}
	}
	var b strings.Builder
	tpl := pageTemplatesFrom("../web/templates")
	if err := tpl.ExecuteTemplate(&b, "root", &templateVars{GoogleAdsenseAccount: "sites-2288675768043065"}); err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(b.String(), `<meta name="google-adsense-account" content="sites-2288675768043065" />`) {
		t.Error("root template: want the google-adsense-account meta")
	}
	b.Reset()
	if err := tpl.ExecuteTemplate(&b, "root", &templateVars{}); err != nil {
		t.Fatal(err)
	}
	if strings.Contains(b.String(), "google-adsense-account") {
		t.Error("root template: adsense meta without an account")
	}
}

func TestApplyClientUISetsHeadbidAffID(t *testing.T) {
	req := middlewares.GetReqWithClientConfig(`{"headbid_aff_id": "128141"}`, &http.Request{})
	config := middlewares.GetClientConfig(req.Context())
	vars := &templateVars{OverrideConfig: template.JS("{}")}
	applyClientUI(vars, config)
	if vars.HeadbidAffId != "128141" {
		t.Fatalf("HeadbidAffId = %q, want 128141", vars.HeadbidAffId)
	}

	none := middlewares.GetClientConfig(middlewares.GetReqWithClientConfig(`{}`, &http.Request{}).Context())
	vars = &templateVars{OverrideConfig: template.JS("{}")}
	applyClientUI(vars, none)
	if vars.HeadbidAffId != "" {
		t.Fatalf("HeadbidAffId = %q, want empty when not configured", vars.HeadbidAffId)
	}
}

func TestSharedStylesheets(t *testing.T) {
	got := sharedStylesheets(map[string]interface{}{
		"stylesheets": []interface{}{
			"https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap",
			"//cdn.example.test/a.css",
			"  ",
			"http://insecure.test/b.css", // mixed content
			"javascript:alert(1)",
			"/relative.css",
			"https://cdn.example.test/a.css\n/evil.css", // embedded newline
			42,
		},
	})
	want := []string{
		"https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap",
		"//cdn.example.test/a.css",
	}
	if strings.Join(got, "\n") != strings.Join(want, "\n") {
		t.Fatalf("sharedStylesheets = %q, want %q", got, want)
	}
	if got := sharedStylesheets(map[string]interface{}{"stylesheets": "nope"}); got != nil {
		t.Fatalf("non-list stylesheets = %q, want nil", got)
	}
	if got := sharedStylesheets(nil); got != nil {
		t.Fatalf("no shared block = %q, want nil", got)
	}
}

func TestRootTemplateStylesheets(t *testing.T) {
	tpl := pageTemplatesFrom("../web/templates")
	var b strings.Builder
	vars := &templateVars{Stylesheets: []string{"https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&display=swap"}}
	if err := tpl.ExecuteTemplate(&b, "root", vars); err != nil {
		t.Fatal(err)
	}
	html := b.String()
	// "&" is HTML-escaped in the attribute; the browser reads back the
	// original URL, which is what the frontend compares against.
	link := `<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;700&amp;display=swap" />`
	i := strings.Index(html, link)
	if i < 0 {
		t.Fatalf("stylesheet link missing from:\n%s", html)
	}
	if i > strings.Index(html, "</head>") {
		t.Fatalf("stylesheet link is not in <head>")
	}
}

func TestRootTemplateHeadbidMonitor(t *testing.T) {
	tpl := pageTemplatesFrom("../web/templates")
	const script = `<script type="text/javascript" src="https://c.headbid.com/monitor.js?aff=128134"></script>`

	var b strings.Builder
	if err := tpl.ExecuteTemplate(&b, "root", &templateVars{HeadbidAffId: "128134"}); err != nil {
		t.Fatal(err)
	}
	html := b.String()
	if strings.Count(html, script) != 1 || strings.Index(html, script) > strings.Index(html, "</head>") {
		t.Fatalf("expected the headbid monitor script once in <head>:\n%s", html)
	}

	b.Reset()
	if err := tpl.ExecuteTemplate(&b, "root", &templateVars{}); err != nil {
		t.Fatal(err)
	}
	if strings.Contains(b.String(), "monitor.js") {
		t.Fatalf("unexpected headbid script without an affiliate ID")
	}
}

func TestCategoryLabelAndNavOrder(t *testing.T) {
	config := &middlewares.ClientConfig{Raw: map[string]interface{}{
		"shared": map[string]interface{}{"navigation": map[string]interface{}{"staticItems": []interface{}{
			map[string]interface{}{"label": "Home", "url": "/"},
			map[string]interface{}{"label": "Places To Go", "url": "/places-to-go"},
			map[string]interface{}{"label": "Experiences", "url": "/experiences"},
			map[string]interface{}{"label": "Airport Guide", "url": "/airport-guide"},
		}}},
	}}

	if got := categoryLabel(config, "places-to-go", "Places to Go"); got != "Places To Go" {
		t.Errorf("menu label = %q, want %q", got, "Places To Go")
	}
	if got := categoryLabel(config, "not-in-menu", "Not In Menu"); got != "Not In Menu" {
		t.Errorf("unlinked category = %q, want the fallback", got)
	}
	if got := categoryLabel(nil, "places-to-go", "Places to Go"); got != "Places to Go" {
		t.Errorf("no config = %q, want the fallback", got)
	}
	if !menuLinksTo(config, "/experiences") || menuLinksTo(config, "/articles") {
		t.Errorf("menuLinksTo should match only the menu's links")
	}

	// CMS order in, menu order out; categories the menu doesn't link keep their CMS order at the end.
	categories := []sitemapCategory{{Slug: "extra-b"}, {Slug: "airport-guide"}, {Slug: "extra-a"}, {Slug: "experiences"}, {Slug: "places-to-go"}}
	sortCategoriesByNav(config, categories)
	var got []string
	for _, c := range categories {
		got = append(got, c.Slug)
	}
	if want := "places-to-go experiences airport-guide extra-b extra-a"; strings.Join(got, " ") != want {
		t.Errorf("order = %q, want %q", strings.Join(got, " "), want)
	}
}

func TestSearchKeywordTitle(t *testing.T) {
	withLabel := &middlewares.ClientConfig{Raw: map[string]interface{}{
		"shared": map[string]interface{}{"labels": map[string]interface{}{"searchTitle": "Search | {keyword}"}},
	}}
	cases := []struct {
		name    string
		config  *middlewares.ClientConfig
		keyword string
		want    string
	}{
		{"keyword in title case", withLabel, "airbrush", "Search | Airbrush"},
		{"each word, rest kept as typed", withLabel, " car insurance e-commerce ", "Search | Car Insurance E-commerce"},
		{"no keyword", withLabel, "  ", ""},
		{"site without the label", &middlewares.ClientConfig{Raw: map[string]interface{}{}}, "airbrush", ""},
		{"no config", nil, "airbrush", ""},
	}
	for _, c := range cases {
		if got := searchKeywordTitle(c.config, c.keyword); got != c.want {
			t.Errorf("%s: got %q, want %q", c.name, got, c.want)
		}
	}
}
