package routes

import (
	"context"
	"errors"
	"html/template"
	"log"
	"net/http"
	"net/url"
	"reflect"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"time"

	"bitbucket.org/imediabrands/oos-service/middlewares"
)

// legacyURLRules are a site's own rules for the URLs its legacy (PHP) site
// used, from the client config's "legacyUrls" block:
//
//		"legacyUrls": {
//		  "categoryPagination": true,
//		  "redirects": [{"from": "^/site_map/?$", "to": "/sitemap"}],
//		  "gone": ["^/category(/.*)?$"],
//		  "listings": ["^/business/([0-9]+)(?:-[^/]*)?/?$"]
//		}
//
//	  - categoryPagination: /{category}/{n} is page n of the category (a 301 to
//	    /{category}?page=n), not article n (see maxLegacyCategoryPage).
//	  - redirects: 301 a path matching "from" (an anchored regexp) to "to", in
//	    which ${1}, ${2}.. are its groups ("$1" works too, but "$1x" would read as
//	    a group named "1x"). Groups land in the path as they are and in a "to"
//	    query escaped. The request's query is kept, but for keys the "to" query
//	    sets, and on /search the legacy search params are renamed (see
//	    legacySearchRedirectQuery; directorySearchRedirectQuery on directory
//	    sites). On a directory site a "to" that is a directory URL
//	    (/{st}/{city}/...) is sent to its canonical form, so it is one hop.
//	    On a directory site a "to" of /search whose query has s drops the old
//	    keyword/search/q params, so /search?s=x&keyword=x is one clean hop.
//	    A target that would leave the site (see leavesSite) is a 404.
//	  - gone: answer 410 Gone (with the not-found page) for a URL matching any of
//	    these regexps, tested against the path and against path?query.
//	  - listings (directory sites only): old listing URLs by id, group 1 of the
//	    regexp. Tried first: a listing 301s to its url (query dropped), an
//	    unknown id is a 404, an unavailable store the 503 page.
type legacyURLRules struct {
	CategoryPagination bool
	Redirects          []legacyRedirect
	Gone               []*regexp.Regexp
	Listings           []*regexp.Regexp
	// Directory: the site is a directory site (see isDirectorySite).
	Directory bool
}

type legacyRedirect struct {
	From *regexp.Regexp
	To   string
}

// legacyRulesCache keeps each config's parsed rules, keyed by the address of
// its "legacyUrls" map (loaded once at startup), so the regexps compile once
// per client.
var legacyRulesCache sync.Map // map[uintptr]*legacyURLRules

func legacyURLRulesFromConfig(config *middlewares.ClientConfig) *legacyURLRules {
	if config == nil {
		return nil
	}
	block, ok := config.Raw["legacyUrls"].(map[string]interface{})
	if !ok {
		return nil
	}
	key := reflect.ValueOf(block).Pointer()
	if cached, ok := legacyRulesCache.Load(key); ok {
		return cached.(*legacyURLRules)
	}
	rules := parseLegacyURLRules(block)
	rules.Directory = isDirectorySite(config)
	legacyRulesCache.Store(key, rules)
	return rules
}

// parseLegacyURLRules reads a "legacyUrls" block; an invalid regexp is logged
// and skipped, so one bad rule never breaks the site.
func parseLegacyURLRules(block map[string]interface{}) *legacyURLRules {
	rules := &legacyURLRules{}
	rules.CategoryPagination, _ = block["categoryPagination"].(bool)
	redirects, _ := block["redirects"].([]interface{})
	for _, item := range redirects {
		entry, _ := item.(map[string]interface{})
		from, _ := entry["from"].(string)
		to, _ := entry["to"].(string)
		re, err := regexp.Compile(from)
		if err != nil || to == "" {
			log.Printf("[WARN] legacyUrls: skipping redirect %q -> %q: %v", from, to, err)
			continue
		}
		rules.Redirects = append(rules.Redirects, legacyRedirect{From: re, To: to})
	}
	gone, _ := block["gone"].([]interface{})
	for _, item := range gone {
		pattern, _ := item.(string)
		re, err := regexp.Compile(pattern)
		if err != nil || pattern == "" {
			log.Printf("[WARN] legacyUrls: skipping gone pattern %q: %v", pattern, err)
			continue
		}
		rules.Gone = append(rules.Gone, re)
	}
	listingPatterns, _ := block["listings"].([]interface{})
	for _, item := range listingPatterns {
		pattern, _ := item.(string)
		re, err := regexp.Compile(pattern)
		if err == nil && re.NumSubexp() < 1 {
			err = errors.New("no group for the listing id")
		}
		if err != nil || pattern == "" {
			log.Printf("[WARN] legacyUrls: skipping listings pattern %q: %v", pattern, err)
			continue
		}
		rules.Listings = append(rules.Listings, re)
	}
	return rules
}

// listingID returns the listing id an old listing URL names (see
// legacyURLRules.Listings); ok is false when no listings pattern matches.
// A match whose id isn't digits gives "", true: an old listing URL, but no
// listing.
func (rules *legacyURLRules) listingID(path string) (string, bool) {
	if !rules.Directory {
		return "", false
	}
	for _, re := range rules.Listings {
		if m := re.FindStringSubmatch(path); m != nil {
			if !isNumericID(m[1]) {
				return "", true
			}
			return m[1], true
		}
	}
	return "", false
}

// serveLegacyListing answers an old listing URL: a 301 to the listing's url
// (its query dropped), the 404 page for an unknown id, the 503 page while the
// listings store is unavailable.
func serveLegacyListing(w http.ResponseWriter, req *http.Request, tpl *template.Template, id string) {
	if id == "" {
		serveNotFoundPage(w, req, tpl)
		return
	}
	l, found, err := listingsStore.Get(req.Context(), id)
	if err != nil {
		listingsFailed("get "+id, err)
		serveListingsUnavailable(w, req, tpl, "listingDetail", middlewares.GetClientConfig(req.Context()).GetString("displayName"))
		return
	}
	if !found {
		serveNotFoundPage(w, req, tpl)
		return
	}
	redirectPermanently(w, req, l.URL, "")
}

// isGone reports whether a URL matches one of the site's gone patterns.
func (rules *legacyURLRules) isGone(path, rawQuery string) bool {
	withQuery := path
	if rawQuery != "" {
		withQuery += "?" + rawQuery
	}
	for _, re := range rules.Gone {
		if re.MatchString(path) || re.MatchString(withQuery) {
			return true
		}
	}
	return false
}

// redirectTarget returns the path and query a legacy URL redirects to, or ok
// false when no redirect rule matches.
func (rules *legacyURLRules) redirectTarget(path, rawQuery string) (string, string, bool) {
	for _, rule := range rules.Redirects {
		match := rule.From.FindStringSubmatchIndex(path)
		if match == nil {
			continue
		}
		toPath, toQuery, _ := strings.Cut(rule.To, "?")
		targetPath := string(rule.From.ExpandString(nil, toPath, path, match))
		targetQuery := expandEscaped(rule.From, toQuery, path, match)
		query := joinQueries(targetQuery, withoutQueryKeys(rawQuery, targetQuery))
		if targetPath == "/search" {
			rename := legacySearchRedirectQuery
			if rules.Directory {
				rename = directorySearchRedirectQuery
			}
			if renamed, ok := rename(query); ok {
				query = renamed
			} else if rules.Directory && hasQueryKey(query, "s") {
				query = withoutQueryKeys(query, "keyword&search&q")
			}
		}
		// A rule that would send a URL to itself (e.g. /search already on ?term=) is no redirect.
		if targetPath == path && query == rawQuery {
			continue
		}
		return targetPath, query, true
	}
	return "", "", false
}

// expandEscaped is Regexp.ExpandString for a query template: each group is
// query-escaped, so "/search/a%26b" (path "/search/a&b") gives term=a%26b,
// not term=a&b.
func expandEscaped(re *regexp.Regexp, template, src string, match []int) string {
	if template == "" {
		return ""
	}
	var escaped strings.Builder
	indexes := make([]int, len(match))
	for i := 0; i+1 < len(match); i += 2 {
		indexes[i], indexes[i+1] = -1, -1
		if match[i] < 0 {
			continue
		}
		indexes[i] = escaped.Len()
		escaped.WriteString(url.QueryEscape(src[match[i]:match[i+1]]))
		indexes[i+1] = escaped.Len()
	}
	return string(re.ExpandString(nil, template, escaped.String(), indexes))
}

// withoutQueryKeys drops from rawQuery the params whose keys the other query
// sets, keeping the rest as written.
func withoutQueryKeys(rawQuery, other string) string {
	if rawQuery == "" || other == "" {
		return rawQuery
	}
	keys := make(map[string]bool)
	for _, param := range strings.Split(other, "&") {
		key, _, _ := strings.Cut(param, "=")
		keys[key] = true
	}
	kept := make([]string, 0)
	for _, param := range strings.Split(rawQuery, "&") {
		if key, _, _ := strings.Cut(param, "="); !keys[key] {
			kept = append(kept, param)
		}
	}
	return strings.Join(kept, "&")
}

// hasQueryKey reports whether a raw query has a param with this key.
func hasQueryKey(rawQuery, key string) bool {
	for _, param := range strings.Split(rawQuery, "&") {
		if k, _, _ := strings.Cut(param, "="); k == key {
			return true
		}
	}
	return false
}

// joinQueries joins two raw queries, either of which may be empty.
func joinQueries(a, b string) string {
	if a == "" || b == "" {
		return a + b
	}
	return a + "&" + b
}

// maxLegacyCategoryPage is the highest legacy page number: the legacy sites'
// listings have well under 1,000 pages, and their article IDs are higher, so a
// bare article ID (/{category}/5677) is never taken for a page.
const maxLegacyCategoryPage = 1000

// legacyCategoryPagePath returns where a legacy category page URL,
// /{category}/{n} (optionally with a trailing slash), redirects:
// /{category}?page=n, or plain /{category} for page 1. ok is false for any
// other path. Whether {category} is the site's is checked by the caller.
func legacyCategoryPagePath(path, rawQuery string) (category, target, query string, ok bool) {
	parts := strings.Split(strings.Trim(path, "/"), "/")
	if len(parts) != 2 || parts[0] == "" || !isNumericID(parts[1]) {
		return "", "", "", false
	}
	page, err := strconv.Atoi(parts[1])
	if err != nil || page < 1 || page > maxLegacyCategoryPage {
		return "", "", "", false
	}
	query = rawQuery
	if page > 1 {
		values, err := url.ParseQuery(rawQuery)
		if err != nil {
			return "", "", "", false
		}
		if values.Has("page") {
			return "", "", "", false
		}
		query = joinQueries(rawQuery, "page="+parts[1])
	}
	return parts[0], "/" + parts[0], query, true
}

// LegacyURLMiddleware applies the site's legacyUrls rules (see legacyURLRules)
// before routing: gone URLs answer 410, legacy URLs 301 to their pages here.
// Sites without the block are untouched.
func LegacyURLMiddleware(next http.Handler) http.Handler {
	return legacyURLMiddleware(next, pageTemplates())
}

// legacyURLMiddleware is LegacyURLMiddleware rendering gone pages with tpl.
func legacyURLMiddleware(next http.Handler, tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.Method != http.MethodGet && req.Method != http.MethodHead {
			next.ServeHTTP(w, req)
			return
		}
		if serveShopIndexPHPRedirect(w, req) {
			return
		}
		rules := legacyURLRulesFromConfig(middlewares.GetClientConfig(req.Context()))
		if rules == nil {
			next.ServeHTTP(w, req)
			return
		}
		path, rawQuery := req.URL.Path, req.URL.RawQuery

		if id, ok := rules.listingID(path); ok {
			serveLegacyListing(w, req, tpl, id)
			return
		}
		if rules.isGone(path, rawQuery) {
			serveNotFoundPage(goneStatusWriter{w}, req, tpl)
			return
		}
		if target, query, ok := rules.redirectTarget(path, rawQuery); ok {
			// A group that starts with "/" (/index.php//evil.com) would
			// make the target another host: never redirect there.
			if leavesSite(target) {
				serveNotFoundPage(w, req, tpl)
				return
			}
			// The target's own canonical form, so the redirect is one hop; a
			// target that is no page is a 404 here, not a 301 to one.
			target, found := canonicalLegacyTarget(req, rules, target)
			if !found {
				serveNotFoundPage(w, req, tpl)
				return
			}
			if target != path || query != rawQuery {
				redirectPermanently(w, req, target, query)
				return
			}
		}
		if rules.CategoryPagination {
			if category, target, query, ok := legacyCategoryPagePath(path, rawQuery); ok && !categoryRouteMissing(req, category, "") {
				redirectPermanently(w, req, target, query)
				return
			}
		}
		next.ServeHTTP(w, req)
	})
}

// leavesSite reports whether a redirect to path would leave the site: path
// starts with "//" or "/\" (browsers read both as another host), as it is or
// once percent-decoded (a path still encoded after maxLeavesSiteDecodes rounds
// counts too), with the tabs and newlines browsers drop removed.
func leavesSite(path string) bool {
	for i := 0; ; i++ {
		clean := strings.Map(func(r rune) rune {
			if r == '\t' || r == '\n' || r == '\r' {
				return -1
			}
			return r
		}, path)
		if strings.HasPrefix(clean, "//") || strings.HasPrefix(clean, "/\\") {
			return true
		}
		decoded, err := url.PathUnescape(path)
		if err != nil || decoded == path {
			return false
		}
		if i == maxLeavesSiteDecodes {
			return true
		}
		path = decoded
	}
}

// maxLeavesSiteDecodes is how many rounds of percent-decoding leavesSite
// follows; no real target is encoded that deep.
const maxLeavesSiteDecodes = 3

// legacyArticleLookupTimeout bounds the CMS lookup of a legacy redirect to an
// article URL (see canonicalLegacyTarget), well inside the server's write
// timeout: past it the redirect goes to the plain target.
const legacyArticleLookupTimeout = 2 * time.Second

// canonicalLegacyTarget returns the canonical form of a legacy redirect's
// target path, as its page would 301 to it, on a directory site: a directory
// URL (state, city, browse or listing page, see canonicalDirectoryPath), or an
// article URL (see resolveArticleRoute; within legacyArticleLookupTimeout).
// found is false when that page would be a 404. Any other target, one whose
// page can't tell (store unavailable, CMS request failed or too slow), and
// every target on other sites, is returned as it is.
func canonicalLegacyTarget(req *http.Request, rules *legacyURLRules, target string) (canonical string, found bool) {
	if !rules.Directory {
		return target, true
	}
	config := middlewares.GetClientConfig(req.Context())
	if isDirectoryPath(target) {
		if canonical, found, ok := canonicalDirectoryPath(req.Context(), target, directorySettingsFrom(config)); ok {
			return canonical, found
		}
		return target, true
	}
	params, ok := articleRouteParams(target)
	if !ok {
		return target, true
	}
	// The CMS client can't be cancelled: the lookup carries on (and fills
	// the cache) after a timeout, on its own copy of the request.
	ctx, cancel := context.WithTimeout(req.Context(), legacyArticleLookupTimeout)
	defer cancel()
	lookup := req.WithContext(ctx)
	resolved := make(chan articleRoute, 1)
	go func() { resolved <- resolveArticleRoute(lookup, config, params, target) }()
	var route articleRoute
	select {
	case route = <-resolved:
	case <-ctx.Done():
		log.Printf("[WARN] legacyUrls: article lookup for %s: %v; redirecting to it as it is", target, ctx.Err())
		return target, true
	}
	switch {
	case route.NotFoundPage, route.Missing && route.Redirect == "":
		return "", false
	case route.Redirect != "":
		return route.Redirect, true
	}
	return target, true
}

// goneStatusWriter turns the not-found page's 404 into 410 Gone.
type goneStatusWriter struct {
	http.ResponseWriter
}

func (w goneStatusWriter) WriteHeader(statusCode int) {
	if statusCode == http.StatusNotFound {
		statusCode = http.StatusGone
	}
	w.ResponseWriter.WriteHeader(statusCode)
}
