package routes

import (
	"context"
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"

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

const defaultShopAPIBaseURL = "https://api.rebates.com"

// shopAPIBaseURL returns the configured shop API base URL (no trailing slash).
func shopAPIBaseURL() string {
	if u := strings.TrimRight(viper.GetString("shop_api_base_url"), "/"); u != "" {
		return u
	}
	return defaultShopAPIBaseURL
}

// shopUpstreamTimeout bounds a shop API request. It stays below the server's
// WriteTimeout (10s, main.go), so a slow upstream gets an answer from us
// (502, or the page without its product) rather than a cut connection.
const shopUpstreamTimeout = 8 * time.Second

// shopClient is a shared HTTP client with a sensible timeout for proxying
// requests to the shop API.
var shopClient = &http.Client{Timeout: shopUpstreamTimeout}

const (
	// shopCacheTTL is how long a shop API answer is reused.
	shopCacheTTL = 5 * time.Minute
	// shopCacheMaxEntries caps the cache: search URLs come from visitors.
	shopCacheMaxEntries = 2000
)

// shopCache holds the shop API's 200 answers by URL (the affiliate, where
// one is sent, is in the URL), and its 404s under shopMissingKey.
var shopCache = cache.NewWithLimit(shopCacheTTL, shopCacheMaxEntries)

// shopMissingKey is the shopCache key recording that the shop API answered
// targetURL with 404 (a dead SKU, which crawlers keep asking for).
func shopMissingKey(targetURL string) string {
	return "404 " + targetURL
}

// shopGet fetches a shop API URL with the API key, through shopCache: a 200
// or 404 seen in the last shopCacheTTL is answered from it. err is set when
// there was no answer (timeout, connection, body); status is upstream's
// status code otherwise, and body its body.
func shopGet(ctx context.Context, targetURL string) (status int, body []byte, err error) {
	if body, ok := shopCache.Get(targetURL); ok {
		return http.StatusOK, body, nil
	}
	if _, ok := shopCache.Get(shopMissingKey(targetURL)); ok {
		return http.StatusNotFound, nil, nil
	}
	log.Printf("[INFO] shopGet: fetching %s", targetURL)

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
	if err != nil {
		return 0, nil, err
	}
	req.Header.Set("X-API-KEY", viper.GetString("shop_api_key"))

	resp, err := shopClient.Do(req)
	if err != nil {
		return 0, nil, err
	}
	defer resp.Body.Close()

	body, err = io.ReadAll(resp.Body)
	if err != nil {
		return 0, nil, err
	}
	switch resp.StatusCode {
	case http.StatusOK:
		shopCache.Set(targetURL, body)
	case http.StatusNotFound:
		shopCache.Set(shopMissingKey(targetURL), nil)
	}
	return resp.StatusCode, body, nil
}

// proxyShop fetches the given shop API URL and writes the JSON response to w.
func proxyShop(w http.ResponseWriter, req *http.Request, targetURL string) {
	status, body, err := shopGet(req.Context(), targetURL)
	if err != nil {
		log.Printf("[ERROR] proxyShop: %v", err)
		http.Error(w, "failed to fetch shop data", http.StatusBadGateway)
		return
	}

	if status != http.StatusOK {
		log.Printf("[WARN] proxyShop: upstream returned %d for %s", status, targetURL)
		http.Error(w, fmt.Sprintf("upstream returned %d", status), status)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Cache-Control", "public, max-age=300")
	w.Write(body)
}

// ---------------------------------------------------------------------------
// Data API handlers — proxied to the shop API
// ---------------------------------------------------------------------------

// DataShopHomePageHandler proxies GET /data/shop/homepage
func DataShopHomePageHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		proxyShop(w, req, shopAPIBaseURL()+"/commonshop/getHomePageData")
	})
}

// DataShopMasterCategoriesHandler proxies GET /data/shop/mastercategories
func DataShopMasterCategoriesHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		proxyShop(w, req, shopAPIBaseURL()+"/commonshop/getMasterCategories")
	})
}

// DataShopSearchHandler proxies GET /data/shop/search?<params>
func DataShopSearchHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		target := shopAPIBaseURL() + "/commonshop/search"
		if raw := req.URL.RawQuery; raw != "" {
			target += "?" + raw
		}
		proxyShop(w, req, target)
	})
}

// DataShopProductHandler proxies GET /data/shop/product/:sku?affiliate=<id>
func DataShopProductHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		params := httprouter.ParamsFromContext(req.Context())
		sku := params.ByName("sku")
		if sku == "" {
			http.Error(w, "sku is required", http.StatusBadRequest)
			return
		}

		affiliate := strings.TrimSpace(req.URL.Query().Get("affiliate"))
		if affiliate == "" {
			affiliate = shopAffiliateFromConfig(middlewares.GetClientConfig(req.Context()))
		}

		proxyShop(w, req, shopProductURL(sku, affiliate))
	})
}

// shopSuggestEmpty is /data/shop/suggest's answer while no upstream
// endpoint is configured: no suggestions.
const shopSuggestEmpty = `{"success":true,"data":[]}`

// DataShopSuggestHandler serves GET /data/shop/suggest?keyword=, the
// "Customers Also Searched" terms for a keyword search. The shop API has no
// such endpoint yet: until the global config sets shop_suggest_path (e.g.
// "/commonshop/suggest") it answers shopSuggestEmpty, then it proxies
// {shop_api_base_url}{shop_suggest_path}?keyword=.
func DataShopSuggestHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		path := strings.TrimSpace(viper.GetString("shop_suggest_path"))
		if path == "" {
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			w.Header().Set("Cache-Control", "public, max-age=300")
			io.WriteString(w, shopSuggestEmpty)
			return
		}
		if !strings.HasPrefix(path, "/") {
			path = "/" + path
		}
		target := shopAPIBaseURL() + path + "?keyword=" + url.QueryEscape(req.URL.Query().Get("keyword"))
		proxyShop(w, req, target)
	})
}

// shopAffiliateFromConfig is the site's shop affiliate: shared.shop.affiliate
// (what the frontend sends), else the older top-level shop_affiliate.
func shopAffiliateFromConfig(config *middlewares.ClientConfig) string {
	if config == nil {
		return ""
	}
	if affiliate := strings.TrimSpace(config.GetString("shared.shop.affiliate")); affiliate != "" {
		return affiliate
	}
	return strings.TrimSpace(config.GetString("shop_affiliate"))
}

// ---------------------------------------------------------------------------
// Page handlers — serve the React SPA shell
// ---------------------------------------------------------------------------

type shopPageProps struct {
	StartContentServiceOrigin string `json:"startContentServiceOrigin,omitempty"`
	PortalStaticOrigin        string `json:"portalStaticOrigin,omitempty"`
	SiteId                    string `json:"siteId,omitempty"`
	TesseractClient           string `json:"tesseractClient,omitempty"`
	DisplayName               string `json:"displayName,omitempty"`
	GaId                      string `json:"gaId,omitempty"`
	Sku                       string `json:"sku,omitempty"`
	Title                     string `json:"title,omitempty"`
}

func buildShopPageVars(w http.ResponseWriter, req *http.Request, component, pageTitle, metaDescription string, extraProps map[string]string, breadcrumbs []breadcrumbItem) (*templateVars, error) {
	config := middlewares.GetClientConfig(req.Context())
	if config == nil {
		return nil, fmt.Errorf("client config not found")
	}

	displayName := config.GetString("displayName")
	siteId := config.GetString("siteId")
	ga := gaSettingsFromConfig(config)
	tesseractClient := config.GetString("tesseractClient")
	tesseractCdnUrl := config.GetString("tesseract_cdn_url")
	portalStaticCdnUrl := config.GetString("portal_static_cdn_url")
	scsUrl := config.GetString("scs_url")

	if tesseractCdnUrl == "" {
		tesseractCdnUrl = "/static/tesseract"
	}

	hostname, _ := os.Hostname()
	deviceType := "\"desktop\""
	environment := "\"" + config.GetString("environment") + "\""

	props := shopPageProps{
		StartContentServiceOrigin: scsUrl,
		PortalStaticOrigin:        portalStaticCdnUrl,
		SiteId:                    siteId,
		TesseractClient:           tesseractClient,
		DisplayName:               displayName,
		GaId:                      ga.GaId,
	}
	if extraProps != nil {
		if v, ok := extraProps["sku"]; ok {
			props.Sku = v
		}
		if v, ok := extraProps["title"]; ok {
			props.Title = v
		}
	}
	propsJSON, _ := json.Marshal(props)

	overrideConfig := map[string]interface{}{
		"siteId":             siteId,
		"displayName":        displayName,
		"seoMeta":            config.GetStringMap("seoMeta"),
		"logoUrl":            logoURLFromConfig(config),
		"articleTitleSuffix": articleTitleSuffixFromConfig(config),
	}
	configJSON, _ := json.Marshal(overrideConfig)

	vars := &templateVars{
		PageTitle:              pageTitle + " - " + displayName,
		MetaDescription:        metaDescription,
		FaviconUrl:             faviconURLFromConfig(config),
		DNSPrefetch:            []string{tesseractCdnUrl, scsUrl, portalStaticCdnUrl},
		CanonicalUrl:           canonicalURL(req),
		TesseractCdnUrl:        tesseractCdnUrl,
		TesseractClient:        tesseractClient,
		SingleCubeComponent:    "\"" + component + "\"",
		SingleCubeProps:        template.JS(string(propsJSON)),
		OverrideConfig:         template.JS(string(configJSON)),
		DeviceType:             deviceType,
		Environment:            environment,
		TsuahComment:           template.HTML(fmt.Sprintf("<!-- TSUAH: %s -->", hostname)),
		GaId:                   ga.GaId,
		GaGtm:                  ga.GaGtm,
		GaCx:                   ga.GaCx,
		GtmId:                  ga.GtmId,
		GoogleCsa:              ga.GoogleCsa,
		GoogleSiteVerification: googleSiteVerificationFromConfig(config),
	}
	applyMetaRobots(w, vars, req, metaRobotsIndexable)
	applyClientUI(vars, config)
	applyStructuredData(vars, config, req, breadcrumbs)
	return vars, nil
}

// legacyShopListingParams are the query keys of the legacy PHP sites' shop
// listing, which they serve at /shop itself (/shop?keyword=&master_category=
// &category=&brand=&prices=&condition=&max_shipping=&page=&limit=21&sort=).
var legacyShopListingParams = []string{"keyword", "master_category", "category", "brand", "prices", "condition", "max_shipping", "page", "limit", "sort"}

// isLegacyShopListing reports whether a /shop query is a legacy listing:
// one of its keys has a value (other params, e.g. utm_*, keep the shop home).
func isLegacyShopListing(query url.Values) bool {
	for _, key := range legacyShopListingParams {
		if query.Get(key) != "" {
			return true
		}
	}
	return false
}

// ShopHomeHandler serves GET /shop. A legacy listing URL (see
// isLegacyShopListing) 301s to /shop/search with its query as written,
// which reads the same keys.
func ShopHomeHandler() http.Handler {
	tpl := pageTemplates()
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		if !isShopSite(middlewares.GetClientConfig(req.Context())) && isLegacyShopListing(req.URL.Query()) {
			redirectPermanently(w, req, "/shop/search", req.URL.RawQuery)
			return
		}
		breadcrumbs := []breadcrumbItem{homeBreadcrumbItem(req), {Name: "Shop", URL: canonicalURL(req)}}
		vars, err := buildShopPageVars(w, req, "singlecube.ShopHome", "Shop", "Browse our shop", nil, breadcrumbs)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}

// ShopSearchHandler serves GET /shop/search
func ShopSearchHandler() http.Handler {
	tpl := pageTemplates()
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		breadcrumbs := []breadcrumbItem{
			homeBreadcrumbItem(req),
			{Name: "Shop", URL: absoluteURL(req, "/shop")},
			{Name: "Search Results", URL: canonicalURL(req)},
		}
		vars, err := buildShopPageVars(w, req, "singlecube.ShopSearch", "Shop Search", "Search our shop", nil, breadcrumbs)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}

// LegacyShopProductDetailsHandler 301s the legacy PHP sites' product URL,
// /shop/product_details/:sku/:title, to /shop/product-details/:sku/:title
// (query kept), so links to the old shop pages keep working with one URL per product.
func LegacyShopProductDetailsHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		params := httprouter.ParamsFromContext(req.Context())
		path := "/shop/product-details/" + params.ByName("sku") + "/" + params.ByName("title")
		redirectPermanently(w, req, path, req.URL.RawQuery)
	})
}

// LegacyShopRedirectHandler serves the legacy PHP sites' product link,
// /shop/redirect/:sku (live: a 302 to the merchant), as a 301 to the
// product's page, /shop/product-details/:sku/:title. A product the shop API
// doesn't have is a 404; when the API can't answer it is a 302 to /shop,
// so no 301 is cached for it. Shop-template sites route the URL as before.
func LegacyShopRedirectHandler() http.Handler {
	return legacyShopRedirectHandler(NotFoundHandler(), pageTemplates())
}

func legacyShopRedirectHandler(other http.Handler, tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		config := middlewares.GetClientConfig(req.Context())
		sku := httprouter.ParamsFromContext(req.Context()).ByName("sku")
		if isShopSite(config) || strings.TrimSpace(sku) == "" {
			other.ServeHTTP(w, req)
			return
		}
		ctx, cancel := context.WithTimeout(req.Context(), shopProductLookupTimeout)
		defer cancel()
		product, err := fetchShopProduct(ctx, sku, shopAffiliateFromConfig(config))
		if err == errShopProductMissing {
			serveNotFoundPage(w, req, tpl)
			return
		}
		if err != nil {
			log.Printf("[WARN] shop redirect %q: %v", sku, err)
			w.Header().Set("Cache-Control", "no-store")
			http.Redirect(w, req, "/shop", http.StatusFound)
			return
		}
		// The URL the frontend's links use (a "/" in the title stays %2F).
		rawPath := "/shop/product-details/" + encodeURIComponent(sku) + "/" + shopTitleSlug(product.Name)
		path, _ := url.PathUnescape(rawPath)
		w.Header().Set("Cache-Control", seoRedirectCacheControl)
		http.Redirect(w, req, (&url.URL{Path: path, RawPath: rawPath, RawQuery: req.URL.RawQuery}).String(), http.StatusMovedPermanently)
	})
}

// ShopProductDetailsHandler serves GET /shop/product-details/:sku/*title.
// The title is one path segment read from the escaped path: the frontend's
// links encode a "/" in a product's title as %2F, and the router matches the
// decoded path, so a :title param would split it (a 404). More segments are
// the not-found page; a trailing slash 301s to the URL without it.
func ShopProductDetailsHandler() http.Handler {
	return shopProductDetailsHandler(NotFoundHandler(), pageTemplates())
}

func shopProductDetailsHandler(other http.Handler, tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		sku := httprouter.ParamsFromContext(req.Context()).ByName("sku")
		segments := strings.Split(strings.TrimPrefix(req.URL.EscapedPath(), "/shop/product-details/"), "/")
		if len(segments) == 3 && segments[1] != "" && segments[2] == "" {
			location := "/shop/product-details/" + segments[0] + "/" + segments[1]
			if req.URL.RawQuery != "" {
				location += "?" + req.URL.RawQuery
			}
			w.Header().Set("Cache-Control", seoRedirectCacheControl)
			http.Redirect(w, req, location, http.StatusMovedPermanently)
			return
		}
		if len(segments) != 2 || segments[1] == "" {
			other.ServeHTTP(w, req)
			return
		}
		title, err := url.PathUnescape(segments[1])
		if err != nil {
			other.ServeHTTP(w, req)
			return
		}
		canonical := absoluteURL(req, "/shop/product-details/"+segments[0]+"/"+segments[1])

		extra := map[string]string{"sku": sku, "title": title}

		pageTitle := "Product Details"
		if title != "" {
			pageTitle = strings.ReplaceAll(title, "-", " ")
		}

		breadcrumbs := []breadcrumbItem{
			homeBreadcrumbItem(req),
			{Name: "Shop", URL: absoluteURL(req, "/shop")},
			{Name: pageTitle, URL: canonical},
		}
		vars, err := buildShopPageVars(w, req, "singlecube.ShopProductDetails", pageTitle, "View product details", extra, breadcrumbs)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		vars.CanonicalUrl = canonical
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		if err := tpl.ExecuteTemplate(w, "root", vars); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})
}
