package routes

import (
	"encoding/json"
	"errors"
	"html/template"
	"io"
	"log"
	"net/http"
	"strings"
	"sync"
	"time"

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

// A site with a legacy quiz site as its content source sets "quiz_source_base_url" in its
// client config ("https://aboutharmony.com", or the legacy origin once the domain points here).
// oos-service then serves the legacy site's quizzes, polls and listings as JSON and the
// /survey/:slug pages as the frontend shell. Other sites are unaffected: every handler here
// answers like an unknown URL when the site has no quiz source.

const quizPageCacheTTL = 10 * time.Minute

var quizSources sync.Map // base URL -> *quizsource.Source

// quizSourceFor returns the quiz source of the request's site, nil when it has none.
func quizSourceFor(req *http.Request) *quizsource.Source {
	config := middlewares.GetClientConfig(req.Context())
	if config == nil {
		return nil
	}
	base := strings.TrimSpace(config.GetString("quiz_source_base_url"))
	if base == "" || !(strings.HasPrefix(base, "https://") || strings.HasPrefix(base, "http://")) {
		return nil
	}
	if s, ok := quizSources.Load(base); ok {
		return s.(*quizsource.Source)
	}
	s, _ := quizSources.LoadOrStore(base, quizsource.New(base, quizPageCacheTTL))
	return s.(*quizsource.Source)
}

func writeQuizJSON(w http.ResponseWriter, status int, body interface{}) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(body)
}

func quizError(w http.ResponseWriter, err error) {
	if errors.Is(err, quizsource.ErrNotFound) {
		writeQuizJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
		return
	}
	log.Printf("[ERROR] quiz source: %v", err)
	writeQuizJSON(w, http.StatusBadGateway, map[string]string{"error": "quiz source unavailable"})
}

// DataQuizzesHandler serves GET /data/quizzes?path=/celebs: the carousel, list and trending cards
// of the legacy listing page at path ("/" for the homepage), or with ?q=love the legacy search's results.
func DataQuizzesHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		src := quizSourceFor(req)
		if src == nil {
			writeQuizJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
			return
		}
		var (
			listing *quizsource.Listing
			err     error
		)
		if term := req.URL.Query().Get("q"); term != "" {
			listing, err = src.Search(term)
		} else {
			path := req.URL.Query().Get("path")
			if path == "" {
				path = "/"
			}
			listing, err = src.Listing(path)
		}
		if err != nil {
			quizError(w, err)
			return
		}
		w.Header().Set("Cache-Control", "public, max-age=300")
		writeQuizJSON(w, http.StatusOK, map[string]interface{}{"data": listing})
	})
}

// DataQuizHandler serves GET /data/quizzes/:slug: one quiz or poll.
func DataQuizHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		src := quizSourceFor(req)
		if src == nil {
			writeQuizJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
			return
		}
		quiz, err := src.Quiz(httprouter.ParamsFromContext(req.Context()).ByName("slug"))
		if err != nil {
			quizError(w, err)
			return
		}
		w.Header().Set("Cache-Control", "public, max-age=300")
		writeQuizJSON(w, http.StatusOK, map[string]interface{}{"data": quiz})
	})
}

type quizResultRequest struct {
	// Answers are the choices of a finished personality quiz, one per question.
	Answers []quizsource.Choice `json:"answers"`
	// OptionID is the option a poll vote is for.
	OptionID string `json:"optionId"`
}

// DataQuizResultHandler serves POST /data/quizzes/:slug/result. The ids must belong to the quiz,
// so only a real answer of this quiz is ever posted to the legacy site. The legacy site's own
// answer ({"success", "result"}) is returned as it is.
func DataQuizResultHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		src := quizSourceFor(req)
		if src == nil {
			writeQuizJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
			return
		}
		quiz, err := src.Quiz(httprouter.ParamsFromContext(req.Context()).ByName("slug"))
		if err != nil {
			quizError(w, err)
			return
		}
		var body quizResultRequest
		if err := json.NewDecoder(io.LimitReader(req.Body, 1<<16)).Decode(&body); err != nil {
			writeQuizJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid body"})
			return
		}

		var raw json.RawMessage
		switch quiz.Type {
		case quizsource.TypePersonality:
			if !quizAnswersBelong(quiz, body.Answers) {
				writeQuizJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid answers"})
				return
			}
			raw, err = src.PersonalityResult(quiz.DisplayID, body.Answers)
		case quizsource.TypePoll:
			if !quizOptionBelongs(quiz, body.OptionID) {
				writeQuizJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid option"})
				return
			}
			raw, err = src.PollVote(quiz.DisplayID, body.OptionID)
		default:
			writeQuizJSON(w, http.StatusBadRequest, map[string]string{"error": "this page has no result"})
			return
		}
		if err != nil {
			quizError(w, err)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Header().Set("Cache-Control", "no-store")
		_, _ = w.Write(raw)
	})
}

// quizAnswersBelong reports whether choices answer every question of quiz once, with one of its answers.
func quizAnswersBelong(quiz *quizsource.Quiz, choices []quizsource.Choice) bool {
	if len(choices) != len(quiz.Questions) {
		return false
	}
	seen := map[string]bool{}
	for _, c := range choices {
		if seen[c.QuestionID] {
			return false
		}
		seen[c.QuestionID] = true
		ok := false
		for _, q := range quiz.Questions {
			if q.ID != c.QuestionID {
				continue
			}
			for _, a := range q.Answers {
				if a.ID == c.AnswerID {
					ok = true
				}
			}
		}
		if !ok {
			return false
		}
	}
	return true
}

func quizOptionBelongs(quiz *quizsource.Quiz, optionID string) bool {
	for _, q := range quiz.Questions {
		for _, a := range q.Answers {
			if a.ID == optionID {
				return true
			}
		}
	}
	return false
}

// QuizPageHandler serves GET /survey/:slug: the frontend shell with the quiz's title as the page
// title. A quiz the legacy site does not have is the site's not-found page.
func QuizPageHandler() http.Handler {
	return quizPageHandler(pageTemplates())
}

func quizPageHandler(tpl *template.Template) http.Handler {
	notFound := notFoundHandler(tpl)
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		src := quizSourceFor(req)
		config := middlewares.GetClientConfig(req.Context())
		if src == nil || config == nil {
			notFound.ServeHTTP(w, req)
			return
		}
		quiz, err := src.Quiz(httprouter.ParamsFromContext(req.Context()).ByName("slug"))
		if errors.Is(err, quizsource.ErrNotFound) {
			serveStaticPageShell(w, req, tpl, notFoundPageName)
			return
		}
		title := ""
		if err == nil {
			title = quiz.Title
		} else {
			// The legacy site is down: still serve the shell, the frontend shows its own error.
			log.Printf("[ERROR] quiz page: %v", err)
		}
		displayName := config.GetString("displayName")
		pageTitle := strings.TrimSpace(title + " | " + displayName)
		if title == "" {
			pageTitle = displayName
		}
		vars := pageShellVars(req, config, "quiz", pageTitle, pageTitle)
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		applyMetaRobots(w, vars, req, metaRobotsIndexable)
		applyStructuredData(vars, config, req, []breadcrumbItem{
			homeBreadcrumbItem(req),
			{Name: title, URL: canonicalURL(req)},
		})
		if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}

// QuizAliasHandler redirects the legacy quiz URLs (/topquiz/:slug, /quiz/:slug, /trending/:slug)
// to /survey/:slug on a site with a quiz source, and is an unknown URL on any other.
func QuizAliasHandler() http.Handler {
	return quizAliasHandler(pageTemplates())
}

func quizAliasHandler(tpl *template.Template) http.Handler {
	notFound := notFoundHandler(tpl)
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		slug := httprouter.ParamsFromContext(req.Context()).ByName("slug")
		if quizSourceFor(req) == nil || !quizsource.ValidSlug(slug) {
			notFound.ServeHTTP(w, req)
			return
		}
		http.Redirect(w, req, "/survey/"+slug, http.StatusMovedPermanently)
	})
}
