package routes

import (
	"context"
	"fmt"
	"html/template"
	"net/http"
	"strings"

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

func NotFoundHandler() http.Handler {
	return notFoundHandler(pageTemplates())
}

// notFoundHandler is NotFoundHandler rendering with tpl.
func notFoundHandler(tpl *template.Template) http.Handler {
	articleHandler := articleDetailHandler(tpl)
	categoryHandler := articleByCategoryHandler(tpl)

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if req.Method == http.MethodGet {
			// A page of the site's own (config pages.<name>.path, e.g. /faq).
			if config := middlewares.GetClientConfig(req.Context()); config != nil {
				if pageName := extraPageAt(config.Raw, req.URL.Path); pageName != "" {
					serveStaticPageShell(w, req, tpl, pageName)
					return
				}
			}

			// /{st}/{city}[/...] on a directory site  →  city, browse or listing page
			if serveDirectoryPath(w, req, tpl) {
				return
			}

			// /sitemap_{category}.xml  →  category + articles sitemap
			if tryServeSitemapXML(w, req) {
				return
			}

			// /sitemap/sitemap_{category}.xml (legacy)  →  301 to /sitemap_{category}.xml
			if serveLegacySitemapRedirect(w, req) {
				return
			}

			// /{categorySlug}/{subcategorySlug}/{id}-{slugTitle}  →  article detail nested under a subcategory
			if category, subcategory, slug, ok := parseSubcategoryArticleDetailPath(req.URL.Path); ok {
				params := httprouter.Params{
					httprouter.Param{Key: "category", Value: category},
					httprouter.Param{Key: "subcategory", Value: subcategory},
					httprouter.Param{Key: "slug", Value: slug},
				}
				ctx := context.WithValue(req.Context(), httprouter.ParamsKey, params)
				articleHandler.ServeHTTP(w, req.WithContext(ctx))
				return
			}

			// /{categorySlug}/{id}-{slugTitle}  →  article detail
			if category, slug, ok := parseArticleDetailPath(req.URL.Path); ok {
				params := httprouter.Params{
					httprouter.Param{Key: "category", Value: category},
					httprouter.Param{Key: "slug", Value: slug},
				}
				ctx := context.WithValue(req.Context(), httprouter.ParamsKey, params)
				articleHandler.ServeHTTP(w, req.WithContext(ctx))
				return
			}

			// /{catSlug}/ or /{catSlug}/{subcatSlug}/  →  301 to the same path
			// without the trailing slash. Article URLs are handled above:
			// their canonical redirect already drops the slash in one hop.
			if serveTrailingSlashRedirect(w, req) {
				return
			}

			// /{catSlug}/{subcatSlug}  →  subcategory page (second segment has no leading digit)
			if catSlug, subcatSlug, ok := parseSubcategoryPath(req.URL.Path); ok {
				params := httprouter.Params{
					httprouter.Param{Key: "categorySlug", Value: catSlug},
					httprouter.Param{Key: "subcategorySlug", Value: subcatSlug},
				}
				ctx := context.WithValue(req.Context(), httprouter.ParamsKey, params)
				categoryHandler.ServeHTTP(w, req.WithContext(ctx))
				return
			}

			// /{cat_name_slug}  →  category page (e.g. /wine)
			if slug, ok := parseCategoryPath(req.URL.Path); ok {
				params := httprouter.Params{
					httprouter.Param{Key: "categorySlug", Value: slug},
				}
				ctx := context.WithValue(req.Context(), httprouter.ParamsKey, params)
				categoryHandler.ServeHTTP(w, req.WithContext(ctx))
				return
			}
		}

		serveNotFoundPage(w, req, tpl)
	})
}

// serveNotFoundPage writes the 404 page: site-template sites show their own
// not-found page (header, footer, site styles) from the page shell, other
// sites a plain one; both are noindex.
func serveNotFoundPage(w http.ResponseWriter, req *http.Request, tpl *template.Template) {
	config := middlewares.GetClientConfig(req.Context())

	if config != nil && usesSiteTemplate(config.Raw) {
		serveStaticPageShell(w, req, tpl, notFoundPageName)
		return
	}

	displayName := "this site"
	if config != nil {
		displayName = config.GetString("displayName")
	}

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	setXRobotsTag(w, robotsNoIndexNoFollow)
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprintf(w, `<!doctype html><html><head><title>Page Not Found - %s</title><meta name="robots" content="noindex,nofollow" /></head><body><h1>404 - Page Not Found</h1><p>The page you requested could not be found.</p></body></html>`, displayName)
}

// serveTrailingSlashRedirect 301s a category/subcategory URL with a trailing
// slash to the same path without it, so each listing page has one URL.
// An unknown category gets its 404 directly, not a redirect to one.
// Reports whether it wrote a redirect.
func serveTrailingSlashRedirect(w http.ResponseWriter, req *http.Request) bool {
	target, ok := trailingSlashRedirectPath(req.URL.Path)
	if !ok {
		return false
	}
	category, subcategory, _ := strings.Cut(strings.TrimPrefix(target, "/"), "/")
	if categoryRouteMissing(req, category, subcategory) {
		return false
	}
	redirectPermanently(w, req, target, req.URL.RawQuery)
	return true
}
