package routes

import (
	"html/template"
	"regexp"
	"strings"

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

// gaSettings holds Google Analytics / Tag Manager values from client_configs/*.json:
//   - ga_id      → measurement ID for gtag.js (optional)
//   - ga_cx      → optional cx query param for gtag.js loader
//   - ga_gtm     → optional gtm query param for gtag.js loader
//   - gtm_id     → classic GTM container ID (e.g. GTM-T9B9RFC)
//   - google_csa → when true, load Google Custom Search Ads (_googCsa) scripts
type gaSettings struct {
	GaId      string
	GaCx      string
	GaGtm     string
	GtmId     string
	GoogleCsa bool
}

// gtmContainerIDRe allows only the standard GTM-XXXXXXXX form so the ID is safe
// to interpolate into the shared HTML template.
var gtmContainerIDRe = regexp.MustCompile(`^GTM-[A-Z0-9]+$`)

func gaSettingsFromConfig(config *middlewares.ClientConfig) gaSettings {
	if config == nil {
		return gaSettings{}
	}
	return gaSettings{
		GaId:      config.GetString("ga_id"),
		GaCx:      config.GetString("ga_cx"),
		GaGtm:     config.GetString("ga_gtm"),
		GtmId:     sanitizeGtmID(config.GetString("gtm_id")),
		GoogleCsa: config.GetBool("google_csa"),
	}
}

func sanitizeGtmID(id string) string {
	id = strings.TrimSpace(id)
	if !gtmContainerIDRe.MatchString(id) {
		return ""
	}
	return id
}

// gaScriptSrc builds the gtag.js loader URL. Marked template.URL so
// html/template does not re-encode & in query params.
func gaScriptSrc(gaId, gaCx, gaGtm string) template.URL {
	if gaId == "" {
		return ""
	}
	url := "https://www.googletagmanager.com/gtag/js?id=" + gaId
	if gaCx != "" {
		url += "&cx=" + gaCx
	}
	if gaGtm != "" {
		url += "&gtm=" + gaGtm
	}
	return template.URL(url)
}

// pageTemplates loads shared HTML templates for all page handlers.
func pageTemplates() *template.Template {
	return pageTemplatesFrom("web/templates")
}

// pageTemplatesFrom loads the shared HTML templates from tplPath.
func pageTemplatesFrom(tplPath string) *template.Template {
	return template.Must(template.New("base").Funcs(template.FuncMap{
		"preserveComment": func(s string) template.HTML { return template.HTML(s) },
		"gaScriptSrc":     gaScriptSrc,
	}).ParseFiles(tplPath+"/root.tmpl", tplPath+"/singlecube_loader.tmpl"))
}
