package quizsource

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

const listingHTML = `
<div class="owl-carousel owl-theme">
  <div class="item"><div class="card">
    <a href="https://legacy.test/survey/first-quiz" title="first-quiz"><img class="x" src="https://img.test/first-large.jpeg"></a>
    <div class="card-body"><a href="https://legacy.test/survey/first-quiz">First &amp; Best Quiz?</a></div> <!-- end card-body -->
  </div> <!-- end card --></div> <!-- end item -->
  <div class="item"><div class="card">
    <a href="https://legacy.test/survey/second-poll"><img src="https://img.test/second-large.jpeg"></a>
    <div class="card-body"><a href="https://legacy.test/survey/second-poll">Second Poll?</a></div>
  </div></div>
</div>
<ul class="list-unstyled" id="article-listing">
  <li class="media d-flex">
    <a href="https://legacy.test/survey/first-quiz"><img class="mr-3" src="https://img.test/first.jpeg" alt=""></a>
    <div class="media-body">
      <span class="post-time text-center">Posted 1 month ago by Ann Lee</span>
      <h5 class="mt-0"><a href="https://legacy.test/survey/first-quiz">First &amp; Best Quiz?</a></h5>
      Which one are you? <b>Find out.</b>
    </div>
  </li>
</ul>
<div class="header"><a href="javascript:void(0)"><b>Trending Today </b><span>Nov 17</span></a></div>
<ul><li><img src="https://img.test/t.jpeg" class="img-fluid"> <a href="https://legacy.test/trending/trend-one" class="headline">Trend One</a> <span>By Fran </span></li></ul>`

func TestParseListing(t *testing.T) {
	l := ParseListing(listingHTML)
	if len(l.Featured) != 2 || l.Featured[0].Slug != "first-quiz" || l.Featured[0].Title != "First & Best Quiz?" || l.Featured[0].Image != "https://img.test/first-large.jpeg" {
		t.Fatalf("featured = %+v", l.Featured)
	}
	if len(l.Items) != 1 {
		t.Fatalf("items = %+v", l.Items)
	}
	it := l.Items[0]
	if it.Slug != "first-quiz" || it.Title != "First & Best Quiz?" || it.Image != "https://img.test/first.jpeg" || it.Description != "Which one are you? Find out." || it.Author != "Ann Lee" || it.Posted != "Posted 1 month ago by Ann Lee" {
		t.Fatalf("item = %+v", it)
	}
	if len(l.Trending) != 1 || l.Trending[0].Slug != "trend-one" || l.Trending[0].Author != "Fran" {
		t.Fatalf("trending = %+v", l.Trending)
	}
}

func TestParseListing_EmptyPageGivesEmptyLists(t *testing.T) {
	l := ParseListing("<html><body>nothing</body></html>")
	if l.Featured == nil || l.Items == nil || l.Trending == nil || len(l.Featured)+len(l.Items)+len(l.Trending)+len(l.Latest) != 0 {
		t.Fatalf("listing = %+v", l)
	}
}

const personalityHTML = `
<script>var quizDisplayId = 1; $.ajax({ url: 'https://legacy.test//results/personalityQuiz', data: {quizDisplayId: "abc123def456", results: x} });</script>
<div id="amwidget-survey"><h3 itemprop="name"><b>What kind of cat are you?</b> </h3>
<div class="panel-body">
 <div class="question-wrap " id="question-wrap-1"><img class="img-fluid" src="https://img.test/q1.jpeg">
  <div class="amwidget-question"><ul><li class="active"><a href="javascript:void(0)"> <span class="badge">1</span> Your ideal nap is...</a></li></ul></div>
  <div class="amwidget-answers"><ul><li class="list-group-item ques-1" id="liOpt_100_201" >On a sofa.</li><li class="list-group-item ques-1" id="liOpt_100_202" >In a box &amp; blanket.</li></ul></div>
 </div>
 <div class="question-wrap hidden" id="question-wrap-2"><img src="https://img.test/q2.jpeg">
  <div class="amwidget-question"><ul><li><a href="javascript:void(0)"><span class="badge">2</span> Your food?</a></li></ul></div>
  <div class="amwidget-answers"><ul><li id="liOpt_101_203" >Fish.</li><li id="liOpt_101_204" >Chicken.</li></ul></div>
 </div>
 <div class="result-wrap hidden"><img id="result_image"></div>
</div></div>
<h4>Share This</h4>
<h3>More from legacy</h3>
<div class="col-md-4 col-6 marginbot-18"><a href="https://legacy.test/quiz/related-one"><img src="//img.test/r1.jpeg" class="img-fluid"/></a><div class="link"><a href="https://legacy.test/quiz/related-one">Related One?</a></div></div>
<div class="col-md-4 col-6 marginbot-18"><a href="https://legacy.test/quiz/what-kind-of-cat-are-you"><img src="//img.test/self.jpeg"/></a><div class="link"><a href="x">Itself</a></div></div>`

func TestParseQuiz_Personality(t *testing.T) {
	q := ParseQuiz("what-kind-of-cat-are-you", personalityHTML)
	if q.Type != TypePersonality || q.Title != "What kind of cat are you?" || q.DisplayID != "abc123def456" {
		t.Fatalf("quiz = %+v", q)
	}
	if len(q.Questions) != 2 {
		t.Fatalf("questions = %+v", q.Questions)
	}
	first := q.Questions[0]
	if first.ID != "100" || first.Text != "Your ideal nap is..." || first.Image != "https://img.test/q1.jpeg" || len(first.Answers) != 2 || first.Answers[1].ID != "202" || first.Answers[1].Text != "In a box & blanket." {
		t.Fatalf("first question = %+v", first)
	}
	if q.Questions[1].ID != "101" || len(q.Questions[1].Answers) != 2 {
		t.Fatalf("second question = %+v", q.Questions[1])
	}
	if q.Image != "https://img.test/q1.jpeg" {
		t.Fatalf("image = %q", q.Image)
	}
	// The quiz itself is left out of its related cards, and a protocol-relative picture gets https.
	if len(q.Related) != 1 || q.Related[0].Slug != "related-one" || q.Related[0].Image != "https://img.test/r1.jpeg" {
		t.Fatalf("related = %+v", q.Related)
	}
}

const pollHTML = `
<script>$.ajax({ type: 'POST', url: 'https://legacy.test/results/poll', data: {quizDisplayId: "0123456789abcdef", resultId: res_id} });</script>
<div id="amwidget-survey" ><h3 itemprop="name"><b>Which snack?</b></h3><div class="panel-body"><div class="question-wrap">
 <img src="https://img.test/poll.jpeg">
 <div class="amwidget-question poll"><ul class="list-group"><li class="active"><a href="#">Which snack?</a></li></ul></div>
 <div class="amwidget-answers poll-results"><ul><li id="liOpt_1" class="list-group-item"><span class="total-title grey">Chips</span></li><li id="liOpt_2" class="list-group-item"><span class="total-title grey">Fruit</span></li></ul></div>
</div><div class="clearfix"></div><h4>Share This</h4>`

func TestParseQuiz_Poll(t *testing.T) {
	q := ParseQuiz("which-snack", pollHTML)
	if q.Type != TypePoll || q.Title != "Which snack?" || q.DisplayID != "0123456789abcdef" || len(q.Questions) != 1 {
		t.Fatalf("quiz = %+v", q)
	}
	ques := q.Questions[0]
	if ques.Text != "Which snack?" || len(ques.Answers) != 2 || ques.Answers[0].ID != "1" || ques.Answers[0].Text != "Chips" {
		t.Fatalf("question = %+v", ques)
	}
}

func TestParseQuiz_OtherTypeHasNoQuestions(t *testing.T) {
	q := ParseQuiz("a-list", `<h3 itemprop="name"><b>A list</b></h3><p>Just text.</p>`)
	if q.Type != TypeOther || q.Title != "A list" || len(q.Questions) != 0 {
		t.Fatalf("quiz = %+v", q)
	}
}

func TestValidation(t *testing.T) {
	for _, p := range []string{"/", "/celebs", "/personalityQuiz", "/food-and-drink"} {
		if !ValidListingPath(p) {
			t.Errorf("ValidListingPath(%q) = false", p)
		}
	}
	for _, p := range []string{"", "celebs", "//evil.test", "/a/b", "/../etc", "/x?y=1", "/a b"} {
		if ValidListingPath(p) {
			t.Errorf("ValidListingPath(%q) = true", p)
		}
	}
	if !ValidSlug("what-kind-of-cat-are-you") || ValidSlug("Bad_Slug") || ValidSlug("../x") || ValidSlug("") {
		t.Error("ValidSlug wrong")
	}
}

func legacyServer(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 == "/search":
			if r.URL.Query().Get("search") != "cats & dogs" {
				http.NotFound(w, r)
				return
			}
			io.WriteString(w, listingHTML)
		case r.URL.Path == "/":
			io.WriteString(w, listingHTML)
		case r.URL.Path == "/survey/what-kind-of-cat-are-you":
			io.WriteString(w, personalityHTML)
		default:
			http.NotFound(w, r)
		}
	}))
	t.Cleanup(srv.Close)
	return srv, &posts
}

func TestSource_ListingAndQuiz(t *testing.T) {
	srv, _ := legacyServer(t)
	s := New(srv.URL+"/", time.Minute)

	l, err := s.Listing("/")
	if err != nil || len(l.Items) != 1 {
		t.Fatalf("Listing = %+v, %v", l, err)
	}
	q, err := s.Quiz("what-kind-of-cat-are-you")
	if err != nil || q.Type != TypePersonality || len(q.Questions) != 2 {
		t.Fatalf("Quiz = %+v, %v", q, err)
	}
	if _, err := s.Quiz("no-such-quiz"); err != ErrNotFound {
		t.Errorf("Quiz(missing) error = %v, want ErrNotFound", err)
	}
	if _, err := s.Quiz("Bad/Slug"); err != ErrNotFound {
		t.Errorf("Quiz(invalid slug) error = %v, want ErrNotFound", err)
	}
	if _, err := s.Listing("/a/b"); err != ErrNotFound {
		t.Errorf("Listing(invalid path) error = %v, want ErrNotFound", err)
	}
}

func TestSource_CachesPages(t *testing.T) {
	hits := 0
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		hits++
		io.WriteString(w, listingHTML)
	}))
	defer srv.Close()
	s := New(srv.URL, time.Minute)
	for i := 0; i < 3; i++ {
		if _, err := s.Listing("/"); err != nil {
			t.Fatal(err)
		}
	}
	if hits != 1 {
		t.Errorf("legacy site was asked %d times, want 1", hits)
	}
}

func TestSource_PostsResults(t *testing.T) {
	srv, posts := legacyServer(t)
	s := New(srv.URL, time.Minute)

	raw, err := s.PersonalityResult("abc123def456", []Choice{{QuestionID: "100", AnswerID: "201"}, {QuestionID: "101", AnswerID: "203"}})
	if err != nil {
		t.Fatal(err)
	}
	var got struct {
		Success bool `json:"success"`
		Result  struct {
			Title string `json:"title"`
		} `json:"result"`
	}
	if err := json.Unmarshal(raw, &got); err != nil || !got.Success || got.Result.Title != "The Sofa Cat" {
		t.Fatalf("result = %s, %v", raw, err)
	}
	if len(*posts) != 1 || !strings.HasPrefix((*posts)[0], "/results/personalityQuiz?") || !strings.Contains((*posts)[0], "quizDisplayId=abc123def456") || !strings.Contains((*posts)[0], "ques_id") {
		t.Fatalf("posts = %v", *posts)
	}

	raw, err = s.PollVote("0123456789abcdef", "1")
	if err != nil || !strings.Contains(string(raw), `"count":"3"`) {
		t.Fatalf("vote = %s, %v", raw, err)
	}
	if !strings.Contains((*posts)[1], "resultId=1") {
		t.Fatalf("posts = %v", *posts)
	}
}

func TestSource_RejectsBadResultInput(t *testing.T) {
	srv, posts := legacyServer(t)
	s := New(srv.URL, time.Minute)
	cases := []func() error{
		func() error { _, e := s.PersonalityResult("NOT-HEX!", []Choice{{"1", "2"}}); return e },
		func() error { _, e := s.PersonalityResult("abc123def456", nil); return e },
		func() error { _, e := s.PersonalityResult("abc123def456", []Choice{{"1; DROP", "2"}}); return e },
		func() error { _, e := s.PollVote("abc123def456", "x"); return e },
		func() error { _, e := s.PollVote("zz", "1"); return e },
	}
	for i, c := range cases {
		if err := c(); err != ErrNotFound {
			t.Errorf("case %d: error = %v, want ErrNotFound", i, err)
		}
	}
	if len(*posts) != 0 {
		t.Errorf("bad input reached the legacy site: %v", *posts)
	}
}

func TestSource_Search(t *testing.T) {
	srv, _ := legacyServer(t)
	s := New(srv.URL, time.Minute)
	l, err := s.Search("  cats & dogs ")
	if err != nil || len(l.Items) != 1 {
		t.Fatalf("Search = %+v, %v", l, err)
	}
	for _, term := range []string{"", "   ", strings.Repeat("x", 81)} {
		if _, err := s.Search(term); err != ErrNotFound {
			t.Errorf("Search(%q) error = %v, want ErrNotFound", term, err)
		}
	}
}

func TestParseQuizListPageUsesPageTitle(t *testing.T) {
	page := `<title>6 Facts of Badlands | aboutharmony</title><span class="created-by">Created by <a href="/x">Abhi</a></span><span class="created-date">on March 14, 2018</span>`
	q := ParseQuiz("six-facts", page)
	if q.Title != "6 Facts of Badlands" || q.Type != TypeOther || q.Author != "Abhi" || q.Created != "March 14, 2018" {
		t.Fatalf("quiz = %+v", q)
	}
	// The legacy site's homepage, served for an unknown slug, has no byline: no quiz.
	if q := ParseQuiz("nope", `<title>Make Your Own Quiz | aboutharmony</title>`); q.Title != "" {
		t.Fatalf("homepage parsed as a quiz: %+v", q)
	}
}
