package routes

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

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

func TestLoadCMSCategories_ParsesNewBytesOnly(t *testing.T) {
	body := `{"data":{"parse-test.com":[{"cat_id":"1","cat_name":"First"}]}}`
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte(body))
	}))
	defer srv.Close()
	orig := cmsService
	cmsService = cms.NewService(srv.URL, "test-key", 0)
	defer func() { cmsService = orig }()

	load := func() map[string]interface{} {
		t.Helper()
		response, err := loadCMSCategories()
		if err != nil {
			t.Fatal(err)
		}
		return response
	}

	first := load()
	if reflect.ValueOf(load()).Pointer() != reflect.ValueOf(first).Pointer() {
		t.Error("same bytes were parsed again")
	}

	body = `{"data":{"parse-test.com":[{"cat_id":"2","cat_name":"Second"}]}}`
	categories := extractSitemapCategories(load(), "parse-test.com")
	if len(categories) != 1 || categories[0].Slug != "second" {
		t.Errorf("after a CMS change: categories = %+v, want second", categories)
	}
}

func TestArticleByCategoryHandler_UnknownCategory(t *testing.T) {
	failCMS := false
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if failCMS {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.Write([]byte(`{"data":{
			"411atkins.com":[{"cat_id":"1","cat_name":"Claims Guide","subcategories":[{"id":"7","name":"Car Claims"}]}],
			"other.com":[{"cat_id":"2","cat_name":"Other Topic","subcategories":[{"id":"8","name":"Other Sub"}]}]
		}}`))
	}))
	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 := articleByCategoryHandler(pageTemplatesFrom("../web/templates"))
	serve := func(host, referer string, params httprouter.Params) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodGet, "https://"+host+"/page", nil)
		if referer != "" {
			req.Header.Set("Referer", referer)
		}
		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
	}
	category := func(slug string) httprouter.Params {
		return httprouter.Params{{Key: "categorySlug", Value: slug}}
	}
	subcategory := func(slug, sub string) httprouter.Params {
		return httprouter.Params{{Key: "categorySlug", Value: slug}, {Key: "subcategorySlug", Value: sub}}
	}

	for _, tt := range []struct {
		name    string
		host    string
		referer string
		params  httprouter.Params
		want    int
	}{
		{"category", "411atkins.com", "", category("claims-guide"), http.StatusOK},
		{"subcategory name as a category", "411atkins.com", "", category("car-claims"), http.StatusOK},
		{"subcategory", "411atkins.com", "", subcategory("claims-guide", "car-claims"), http.StatusOK},
		{"visitor from another website", "411atkins.com", "https://other.com/x", category("claims-guide"), http.StatusOK},
		{"legacy route by another CMS id", "411atkins.com", "", httprouter.Params{{Key: "category", Value: "12345"}}, http.StatusNotFound},
		{"legacy route by another site's CMS id", "411atkins.com", "", httprouter.Params{{Key: "category", Value: "2"}}, http.StatusNotFound},
		{"legacy route by the site's category id", "411atkins.com", "", httprouter.Params{{Key: "category", Value: "1"}}, http.StatusMovedPermanently},
		{"legacy route by the site's subcategory id", "411atkins.com", "", httprouter.Params{{Key: "category", Value: "7"}}, http.StatusMovedPermanently},
		{"site the CMS doesn't list", "notlisted.com", "", category("anything"), http.StatusOK},
		{"unknown category", "411atkins.com", "", category("zzz-not-a-page"), http.StatusNotFound},
		{"another site's category", "411atkins.com", "", category("other-topic"), http.StatusNotFound},
		{"another site's category, linked from that site", "411atkins.com", "https://other.com/x", category("other-topic"), http.StatusNotFound},
		{"unknown subcategory", "411atkins.com", "", subcategory("claims-guide", "zzz"), http.StatusNotFound},
		{"subcategory under an unknown category", "411atkins.com", "", subcategory("zzz", "car-claims"), http.StatusNotFound},
		{"category name as a subcategory", "411atkins.com", "", subcategory("claims-guide", "claims-guide"), http.StatusNotFound},
	} {
		t.Run(tt.name, func(t *testing.T) {
			rec := serve(tt.host, tt.referer, tt.params)
			if rec.Code != tt.want {
				t.Fatalf("status = %d, want %d", rec.Code, tt.want)
			}
			html := rec.Body.String()
			if tt.want == http.StatusNotFound {
				if got := rec.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" {
					t.Errorf("X-Robots-Tag = %q, want noindex, nofollow", got)
				}
				if strings.Contains(html, `rel="canonical"`) {
					t.Error("not-found page has a canonical")
				}
			}
		})
	}

	// The legacy id URL moves to the category's slug URL, query kept.
	legacyReq := httptest.NewRequest(http.MethodGet, "https://411atkins.com/articles/category/7?page=2", nil)
	legacyCtx := context.WithValue(context.WithValue(legacyReq.Context(), middlewares.ClientConfigKey, config), httprouter.ParamsKey, httprouter.Params{{Key: "category", Value: "7"}})
	legacy := httptest.NewRecorder()
	handler.ServeHTTP(legacy, legacyReq.WithContext(legacyCtx))
	if got := legacy.Header().Get("Location"); got != "/claims-guide/car-claims?page=2" {
		t.Errorf("legacy subcategory id: Location = %q", got)
	}
	// A classic site keeps its legacy id page.
	classic := &middlewares.ClientConfig{ViperConfig: v, Raw: map[string]interface{}{}}
	classicCtx := context.WithValue(context.WithValue(legacyReq.Context(), middlewares.ClientConfigKey, classic), httprouter.ParamsKey, httprouter.Params{{Key: "category", Value: "12345"}})
	classicRec := httptest.NewRecorder()
	handler.ServeHTTP(classicRec, legacyReq.WithContext(classicCtx))
	if classicRec.Code != http.StatusOK {
		t.Errorf("classic site: legacy id page status = %d, want 200", classicRec.Code)
	}

	redirected := func(path string) bool {
		return serveTrailingSlashRedirect(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "https://411atkins.com"+path, nil))
	}
	for path, want := range map[string]bool{
		"/claims-guide/":            true,
		"/claims-guide/car-claims/": true,
		"/zzz-not-a-page/":          false,
		"/claims-guide/zzz/":        false,
	} {
		if got := redirected(path); got != want {
			t.Errorf("trailing slash redirect of %s = %v, want %v", path, got, want)
		}
	}

	// A failed CMS request isn't a missing category.
	failCMS = true
	if rec := serve("411atkins.com", "", category("zzz-not-a-page")); rec.Code != http.StatusOK {
		t.Errorf("failed CMS request: status = %d, want 200", rec.Code)
	}
	if !redirected("/zzz-not-a-page/") {
		t.Error("failed CMS request: trailing slash should still redirect")
	}
}

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

	// Site-template sites: the page shell, so the app shows the site's own not-found page.
	for _, name := range []string{"editorial", "magazine"} {
		rec := serve(map[string]interface{}{"template": name})
		if rec.Code != http.StatusNotFound {
			t.Fatalf("%s: status = %d, want 404", name, rec.Code)
		}
		html := rec.Body.String()
		if !strings.Contains(html, "<title>Page not found - 411atkins.com</title>") || !strings.Contains(html, "singlecube.StaticPage") {
			t.Errorf("%s: want the page shell with the not-found title", name)
		}
	}

	// Other sites, including an unknown template name: the plain 404 page.
	if html := serve(map[string]interface{}{"template": "no-such-template"}).Body.String(); !strings.Contains(html, "<h1>404 - Page Not Found</h1>") {
		t.Error("unknown template: want the plain 404 page")
	}
	rec := serve(map[string]interface{}{})
	if rec.Code != http.StatusNotFound {
		t.Fatalf("classic: status = %d, want 404", rec.Code)
	}
	html := rec.Body.String()
	if !strings.Contains(html, "<h1>404 - Page Not Found</h1>") || strings.Contains(html, "singlecube.") {
		t.Error("classic: want the plain 404 page")
	}
	if got := rec.Header().Get("X-Robots-Tag"); got != "noindex, nofollow" {
		t.Errorf("classic: X-Robots-Tag = %q, want noindex, nofollow", got)
	}
}
