package routes

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

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

func TestLegacyShopProductDetailsHandler(t *testing.T) {
	serve := func(target, sku, title string) *httptest.ResponseRecorder {
		req := httptest.NewRequest(http.MethodGet, target, nil)
		req = req.WithContext(context.WithValue(req.Context(), httprouter.ParamsKey, httprouter.Params{
			{Key: "sku", Value: sku},
			{Key: "title", Value: title},
		}))
		rec := httptest.NewRecorder()
		LegacyShopProductDetailsHandler().ServeHTTP(rec, req)
		return rec
	}

	cases := []struct {
		name, target, sku, title, want string
	}{
		{"plain", "https://womenwire.com/shop/product_details/J36XVR3PGH/Live-And-Let-Die-----DVD---Best-Buy", "J36XVR3PGH", "Live-And-Let-Die-----DVD---Best-Buy", "/shop/product-details/J36XVR3PGH/Live-And-Let-Die-----DVD---Best-Buy"},
		{"query kept", "https://womenwire.com/shop/product_details/J1/Free-Guy?aff=1", "J1", "Free-Guy", "/shop/product-details/J1/Free-Guy?aff=1"},
		// The router decodes the segment; the Location is re-escaped and stays on this site.
		{"escaped title", "https://womenwire.com/shop/product_details/J2/a%20b", "J2", `a b\x`, "/shop/product-details/J2/a%20b%5Cx"},
	}
	for _, c := range cases {
		rec := serve(c.target, c.sku, c.title)
		if rec.Code != http.StatusMovedPermanently {
			t.Errorf("%s: status = %d, want 301", c.name, rec.Code)
		}
		if got := rec.Header().Get("Location"); got != c.want {
			t.Errorf("%s: Location = %q, want %q", c.name, got, c.want)
		}
		if got := rec.Header().Get("Cache-Control"); got != seoRedirectCacheControl {
			t.Errorf("%s: Cache-Control = %q, want %q", c.name, got, seoRedirectCacheControl)
		}
	}
}

func TestIsLegacyShopListing(t *testing.T) {
	cases := []struct {
		query string
		want  bool
	}{
		{"", false},
		{"utm_source=x&gclid=1", false},
		{"keyword=&master_category=&category=&brand=", false},
		{"keyword=headphones", true},
		{"keyword=&master_category=Fashion&limit=21&sort=", true},
		{"prices=2", true},
	}
	for _, c := range cases {
		query, _ := url.ParseQuery(c.query)
		if got := isLegacyShopListing(query); got != c.want {
			t.Errorf("%q: got %v, want %v", c.query, got, c.want)
		}
	}
}

func TestLegacyShopRedirectHandler(t *testing.T) {
	useTestShopAPI(t)
	handler := legacyShopRedirectHandler(otherHandler, pageTemplatesFrom("../web/templates"))
	editorial := testClientConfig(t, `{"displayName": "Editorial Test", "template": "editorial", "shared": {"shop": {"affiliate": "editorialtest.com"}}}`)
	shop := testClientConfig(t, testShopConfig)
	redirect := func(config *middlewares.ClientConfig, sku string) *httptest.ResponseRecorder {
		return serveWith(handler, config, "/shop/redirect/"+sku, httprouter.Params{{Key: "sku", Value: sku}})
	}

	rec := redirect(editorial, "94317661")
	if rec.Code != http.StatusMovedPermanently {
		t.Fatalf("product: status = %d, want 301", rec.Code)
	}
	if got, want := rec.Header().Get("Location"), "/shop/product-details/94317661/FoodSaver-White-Food-Vacuum-Sealer"; got != want {
		t.Errorf("product: Location = %q, want %q", got, want)
	}
	if got := rec.Header().Get("Cache-Control"); got != seoRedirectCacheControl {
		t.Errorf("product: Cache-Control = %q", got)
	}

	// A "/" in the title stays %2F, as in the frontend's links.
	if got := redirect(editorial, "SLASH").Header().Get("Location"); got != "/shop/product-details/SLASH/50%2F55-TV-Stand" {
		t.Errorf("slash title: Location = %q", got)
	}

	if rec := redirect(editorial, "MISSING"); rec.Code != http.StatusNotFound {
		t.Errorf("missing product: status = %d, want 404", rec.Code)
	}
	rec = redirect(editorial, "BROKEN")
	if rec.Code != http.StatusFound || rec.Header().Get("Location") != "/shop" || rec.Header().Get("Cache-Control") != "no-store" {
		t.Errorf("API error: %d %q %q, want 302 to /shop, no-store", rec.Code, rec.Header().Get("Location"), rec.Header().Get("Cache-Control"))
	}
	if rec := redirect(shop, "94317661"); rec.Code != http.StatusTeapot {
		t.Errorf("shop site: status = %d, want the other handler", rec.Code)
	}
}

func TestShopProductDetailsHandler(t *testing.T) {
	handler := shopProductDetailsHandler(otherHandler, pageTemplatesFrom("../web/templates"))
	editorial := testClientConfig(t, `{"displayName": "Editorial Test", "template": "editorial", "shared": {"shop": {"affiliate": "editorialtest.com"}}}`)
	serve := func(target string) *httptest.ResponseRecorder {
		return serveWith(handler, editorial, target, httprouter.Params{{Key: "sku", Value: "B0FK"}})
	}

	for _, c := range []struct{ target, canonical string }{
		{"/shop/product-details/B0FK/TV-Stand", "https://localtest.com/shop/product-details/B0FK/TV-Stand"},
		// An encoded "/" in the title stays in its one segment.
		{"/shop/product-details/B0FK/Shelf-for-50%2F55%22-TV", "https://localtest.com/shop/product-details/B0FK/Shelf-for-50%2F55%22-TV"},
	} {
		rec := serve(c.target)
		if rec.Code != http.StatusOK {
			t.Fatalf("%s: status = %d, want 200", c.target, rec.Code)
		}
		if want := `<link rel="canonical" href="` + c.canonical + `" />`; !strings.Contains(rec.Body.String(), want) {
			t.Errorf("%s: missing %s", c.target, want)
		}
	}

	rec := serve("/shop/product-details/B0FK/TV-Stand/?aff=1")
	if rec.Code != http.StatusMovedPermanently || rec.Header().Get("Location") != "/shop/product-details/B0FK/TV-Stand?aff=1" {
		t.Errorf("trailing slash: %d %q, want 301 without the slash", rec.Code, rec.Header().Get("Location"))
	}
	for _, target := range []string{"/shop/product-details/B0FK/", "/shop/product-details/B0FK/a/b", "/shop/product-details/B0FK//"} {
		if rec := serve(target); rec.Code != http.StatusTeapot {
			t.Errorf("%s: status = %d, want the not-found handler", target, rec.Code)
		}
	}
}
