package routes

import (
	"context"
	"encoding/json"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

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

const quizTestPersonalityPage = `
<script>$.ajax({ url: 'https://legacy.test//results/personalityQuiz', data: {quizDisplayId: "abc123def456", results: x} });</script>
<h3 itemprop="name"><b>What kind of cat are you?</b></h3>
<div class="question-wrap " id="question-wrap-1"><img src="https://img.test/q1.jpeg">
 <div class="amwidget-question"><a href="javascript:void(0)"><span class="badge">1</span> Nap spot?</a></div>
 <ul><li class="ques-1" id="liOpt_100_201" >Sofa.</li><li class="ques-1" id="liOpt_100_202" >Box.</li></ul></div>
<div class="question-wrap hidden" id="question-wrap-2"><img src="https://img.test/q2.jpeg">
 <div class="amwidget-question"><a href="javascript:void(0)"><span class="badge">2</span> Food?</a></div>
 <ul><li id="liOpt_101_203" >Fish.</li><li id="liOpt_101_204" >Chicken.</li></ul></div>
<div class="result-wrap hidden"></div>`

const quizTestPollPage = `
<script>$.ajax({ url: 'https://legacy.test/results/poll', data: {quizDisplayId: "0123456789abcdef", resultId: r} });</script>
<h3 itemprop="name"><b>Which snack?</b></h3><div class="question-wrap">
 <img src="https://img.test/p.jpeg"><div class="amwidget-question poll"><a href="#">Which snack?</a></div>
 <ul><li id="liOpt_1" class="x"><span class="total-title grey">Chips</span></li><li id="liOpt_2" class="x"><span class="total-title grey">Fruit</span></li></ul>
</div><div class="clearfix">`

func quizLegacyServer(t *testing.T) (*httptest.Server, *[]string) {
	t.Helper()
	var posts []string
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		switch {
		case r.Method == http.MethodPost:
			b, _ := io.ReadAll(r.Body)
			posts = append(posts, r.URL.Path+"?"+string(b))
			if r.URL.Path == "/results/poll" {
				io.WriteString(w, `{"success":true,"result":[{"id":"1","count":"3"},{"id":"2","count":"1"}]}`)
			} else {
				io.WriteString(w, `{"success":true,"result":{"title":"The Sofa Cat","description":"d","image_url":"https://img.test/x.jpeg"}}`)
			}
		case r.URL.Path == "/":
			io.WriteString(w, `<ul id="article-listing"><li class="media"><a href="/survey/what-kind-of-cat-are-you"><img src="https://img.test/a.jpeg"></a><div class="media-body"><span class="post-time">Posted 1 day ago by Ann</span><h5><a href="/survey/what-kind-of-cat-are-you">What kind of cat are you?</a></h5>Desc.</div></li></ul>`)
		case r.URL.Path == "/survey/what-kind-of-cat-are-you":
			io.WriteString(w, quizTestPersonalityPage)
		case r.URL.Path == "/survey/which-snack":
			io.WriteString(w, quizTestPollPage)
		default:
			http.NotFound(w, r)
		}
	}))
	t.Cleanup(srv.Close)
	return srv, &posts
}

// quizRequest builds a request for a site whose quiz source is base ("" = a site with none).
func quizRequest(method, target, base, slug string, body string) *http.Request {
	req := httptest.NewRequest(method, target, strings.NewReader(body))
	v := viper.New()
	v.Set("displayName", "AboutHarmony")
	if base != "" {
		v.Set("quiz_source_base_url", base)
	}
	ctx := context.WithValue(req.Context(), middlewares.ClientConfigKey, &middlewares.ClientConfig{ViperConfig: v})
	if slug != "" {
		ctx = context.WithValue(ctx, httprouter.ParamsKey, httprouter.Params{{Key: "slug", Value: slug}})
	}
	return req.WithContext(ctx)
}

func TestDataQuizzesHandler(t *testing.T) {
	srv, _ := quizLegacyServer(t)
	rr := httptest.NewRecorder()
	DataQuizzesHandler().ServeHTTP(rr, quizRequest(http.MethodGet, "/data/quizzes", srv.URL, "", ""))
	if rr.Code != http.StatusOK {
		t.Fatalf("status = %d: %s", rr.Code, rr.Body.String())
	}
	var got struct {
		Data struct {
			Items []struct{ Slug, Title string } `json:"items"`
		} `json:"data"`
	}
	if err := json.Unmarshal(rr.Body.Bytes(), &got); err != nil || len(got.Data.Items) != 1 || got.Data.Items[0].Slug != "what-kind-of-cat-are-you" {
		t.Fatalf("body = %s (%v)", rr.Body.String(), err)
	}

	// A site without a quiz source, and a path that is not a listing page.
	rr = httptest.NewRecorder()
	DataQuizzesHandler().ServeHTTP(rr, quizRequest(http.MethodGet, "/data/quizzes", "", "", ""))
	if rr.Code != http.StatusNotFound {
		t.Errorf("site without a source: status = %d, want 404", rr.Code)
	}
	rr = httptest.NewRecorder()
	DataQuizzesHandler().ServeHTTP(rr, quizRequest(http.MethodGet, "/data/quizzes?path=//evil.test/x", srv.URL, "", ""))
	if rr.Code != http.StatusNotFound {
		t.Errorf("invalid path: status = %d, want 404", rr.Code)
	}
}

func TestDataQuizHandler(t *testing.T) {
	srv, _ := quizLegacyServer(t)
	rr := httptest.NewRecorder()
	DataQuizHandler().ServeHTTP(rr, quizRequest(http.MethodGet, "/data/quizzes/what-kind-of-cat-are-you", srv.URL, "what-kind-of-cat-are-you", ""))
	if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), `"type":"personality"`) || !strings.Contains(rr.Body.String(), `"displayId":"abc123def456"`) {
		t.Fatalf("status %d: %s", rr.Code, rr.Body.String())
	}
	rr = httptest.NewRecorder()
	DataQuizHandler().ServeHTTP(rr, quizRequest(http.MethodGet, "/data/quizzes/missing-quiz", srv.URL, "missing-quiz", ""))
	if rr.Code != http.StatusNotFound {
		t.Errorf("missing quiz: status = %d, want 404", rr.Code)
	}
}

func TestDataQuizResultHandler_Personality(t *testing.T) {
	srv, posts := quizLegacyServer(t)
	post := func(body string) *httptest.ResponseRecorder {
		rr := httptest.NewRecorder()
		DataQuizResultHandler().ServeHTTP(rr, quizRequest(http.MethodPost, "/data/quizzes/what-kind-of-cat-are-you/result", srv.URL, "what-kind-of-cat-are-you", body))
		return rr
	}

	rr := post(`{"answers":[{"questionId":"100","answerId":"201"},{"questionId":"101","answerId":"204"}]}`)
	if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "The Sofa Cat") {
		t.Fatalf("status %d: %s", rr.Code, rr.Body.String())
	}
	if len(*posts) != 1 || !strings.Contains((*posts)[0], "quizDisplayId=abc123def456") {
		t.Fatalf("posts = %v", *posts)
	}

	// Answers that are not this quiz's are never posted to the legacy site.
	for name, body := range map[string]string{
		"unknown answer":     `{"answers":[{"questionId":"100","answerId":"999"},{"questionId":"101","answerId":"204"}]}`,
		"missing a question": `{"answers":[{"questionId":"100","answerId":"201"}]}`,
		"repeated question":  `{"answers":[{"questionId":"100","answerId":"201"},{"questionId":"100","answerId":"202"}]}`,
		"not JSON":           `nope`,
	} {
		if rr := post(body); rr.Code != http.StatusBadRequest {
			t.Errorf("%s: status = %d, want 400", name, rr.Code)
		}
	}
	if len(*posts) != 1 {
		t.Errorf("invalid input reached the legacy site: %v", *posts)
	}
}

func TestDataQuizResultHandler_Poll(t *testing.T) {
	srv, posts := quizLegacyServer(t)
	post := func(body string) *httptest.ResponseRecorder {
		rr := httptest.NewRecorder()
		DataQuizResultHandler().ServeHTTP(rr, quizRequest(http.MethodPost, "/data/quizzes/which-snack/result", srv.URL, "which-snack", body))
		return rr
	}
	rr := post(`{"optionId":"1"}`)
	if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), `"count":"3"`) {
		t.Fatalf("status %d: %s", rr.Code, rr.Body.String())
	}
	if rr := post(`{"optionId":"77"}`); rr.Code != http.StatusBadRequest {
		t.Errorf("option of another poll: status = %d, want 400", rr.Code)
	}
	if len(*posts) != 1 {
		t.Errorf("posts = %v", *posts)
	}
}

func TestQuizAliasHandler(t *testing.T) {
	srv, _ := quizLegacyServer(t)
	handler := quizAliasHandler(pageTemplatesFrom("../web/templates"))
	rr := httptest.NewRecorder()
	handler.ServeHTTP(rr, quizRequest(http.MethodGet, "/topquiz/what-kind-of-cat-are-you", srv.URL, "what-kind-of-cat-are-you", ""))
	if rr.Code != http.StatusMovedPermanently || rr.Header().Get("Location") != "/survey/what-kind-of-cat-are-you" {
		t.Fatalf("status %d, Location %q", rr.Code, rr.Header().Get("Location"))
	}
	// A site without a quiz source treats the URL as any unknown one: no redirect.
	rr = httptest.NewRecorder()
	handler.ServeHTTP(rr, quizRequest(http.MethodGet, "/topquiz/what-kind-of-cat-are-you", "", "what-kind-of-cat-are-you", ""))
	if rr.Code == http.StatusMovedPermanently {
		t.Errorf("a site without a quiz source redirected")
	}
}

func TestQuizPageHandler(t *testing.T) {
	srv, _ := quizLegacyServer(t)
	handler := quizPageHandler(pageTemplatesFrom("../web/templates"))

	rr := httptest.NewRecorder()
	handler.ServeHTTP(rr, quizRequest(http.MethodGet, "https://aboutharmony.test/survey/what-kind-of-cat-are-you", srv.URL, "what-kind-of-cat-are-you", ""))
	if rr.Code != http.StatusOK || !strings.Contains(rr.Body.String(), "<title>What kind of cat are you? | AboutHarmony</title>") {
		t.Fatalf("status %d: %.400s", rr.Code, rr.Body.String())
	}

	rr = httptest.NewRecorder()
	handler.ServeHTTP(rr, quizRequest(http.MethodGet, "https://aboutharmony.test/survey/missing-quiz", srv.URL, "missing-quiz", ""))
	if rr.Code != http.StatusNotFound {
		t.Errorf("missing quiz: status = %d, want 404", rr.Code)
	}
}
