package middlewares

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"net/http"
	"os"
	"regexp"
	"strings"

	"bitbucket.org/imediabrands/oos-service/internal/utils"
	"github.com/spf13/viper"
)

var clientToViperConf = make(map[string]*viper.Viper)
var clientToRaw = make(map[string]map[string]interface{})
var initCalled bool

type ClientConfig struct {
	ViperConfig *viper.Viper
	// Raw is the client's config file decoded as plain JSON, with key case
	// preserved. Viper lowercases every key, so blocks that are passed to the
	// frontend verbatim (shared, pages, theme) are read from here instead.
	Raw map[string]interface{}
}

type clientConfigKey struct{}

var ClientConfigKey = clientConfigKey{}

var siteToClient map[string]string

// ClientConfigMiddleware resolves the incoming request hostname to a client
// config and injects it into the request context. Downstream handlers retrieve
// it via GetClientConfig.
func ClientConfigMiddleware(next http.Handler) http.Handler {

	var pathBlacklistRe = regexp.MustCompile(`^(?i)/?(?:hosts|health-check)(/|$)`)

	clientConfigDir := utils.GetRelativePath() + "client_configs"

	if !initCalled {
		file, err := os.ReadFile(clientConfigDir + "/site_to_client.json")
		if err != nil {
			log.Fatalf("Failed to read site_to_client.json: %s", err)
		}
		siteToClient = make(map[string]string)
		if err := json.Unmarshal(file, &siteToClient); err != nil {
			log.Fatalf("Failed to parse site_to_client.json: %s", err)
		}

		for _, client := range siteToClient {
			v := clientToViperConf[client]
			if v != nil {
				continue
			}
			v = viper.New()
			v.SetConfigName(client)
			v.AddConfigPath("/opt/oos-service/client_configs")
			v.AddConfigPath(clientConfigDir)
			if err := v.ReadInConfig(); err != nil {
				log.Fatalf("Failed to read config for client %q: %s", client, err)
			}
			v.Set("_client", client)
			clientToViperConf[client] = v

			if path := v.ConfigFileUsed(); path != "" {
				raw := map[string]interface{}{}
				if data, err := os.ReadFile(path); err != nil {
					log.Printf("WARN: could not read raw config for client %q: %s", client, err)
				} else if err := json.Unmarshal(data, &raw); err != nil {
					log.Printf("WARN: could not parse raw config for client %q: %s", client, err)
				} else {
					clientToRaw[client] = raw
				}
			}
		}
		initCalled = true
	}

	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {

		if pathBlacklistRe.MatchString(req.URL.Path) {
			next.ServeHTTP(w, req)
			return
		}

		hostFromReq := strings.ToLower(utils.GetHostWithoutPort(req.Host))

		client := siteToClient[hostFromReq]
		if client == "" {
			log.Printf("ERROR: unable to get client config for %s", req.Host)
			http.Error(w, http.StatusText(http.StatusBadRequest)+": Invalid host", http.StatusBadRequest)
			return
		}

		req = req.WithContext(context.WithValue(req.Context(), ClientConfigKey, &ClientConfig{ViperConfig: clientToViperConf[client], Raw: clientToRaw[client]}))

		next.ServeHTTP(w, req)
	})
}

// ResolveToProductionDomain returns the canonical production domain for any
// hostname variant (UAT, www, or production) so CMS data filtering is
// environment-agnostic. Returns host unchanged if no mapping is found.
func ResolveToProductionDomain(host string) string {
	if siteToClient == nil {
		return host
	}

	clientName := siteToClient[host]
	if clientName == "" {
		return host
	}

	// Walk the map and return the first "clean" domain for this client.
	for domain, client := range siteToClient {
		if client != clientName {
			continue
		}
		if strings.HasPrefix(domain, "www.") ||
			strings.HasPrefix(domain, "uat-") ||
			domain == "localhost" {
			continue
		}
		return domain
	}

	// Fallback: nothing clean found, return original.
	return host
}

// ProductionDomains returns the canonical production domain of every site in
// site_to_client.json. It is empty until ClientConfigMiddleware has loaded it.
func ProductionDomains() []string {
	seen := make(map[string]bool)
	domains := make([]string, 0, len(siteToClient))
	for host := range siteToClient {
		domain := ResolveToProductionDomain(host)
		if !seen[domain] {
			seen[domain] = true
			domains = append(domains, domain)
		}
	}
	return domains
}

// AllClientConfigs returns every client config loaded by ClientConfigMiddleware.
func AllClientConfigs() []*ClientConfig {
	out := make([]*ClientConfig, 0, len(clientToViperConf))
	for client, v := range clientToViperConf {
		out = append(out, &ClientConfig{ViperConfig: v, Raw: clientToRaw[client]})
	}
	return out
}

func GetClientConfig(ctx context.Context) *ClientConfig {
	if v, ok := ctx.Value(ClientConfigKey).(*ClientConfig); ok {
		return v
	}
	return nil
}

func (cc *ClientConfig) GetString(key string) string {
	if cc.ViperConfig.IsSet(key) {
		return cc.ViperConfig.GetString(key)
	}
	return viper.GetString(key)
}

func (cc *ClientConfig) GetBool(key string) bool {
	if cc.ViperConfig.IsSet(key) {
		return cc.ViperConfig.GetBool(key)
	}
	return viper.GetBool(key)
}

func (cc *ClientConfig) GetStringSlice(key string) []string {
	if cc.ViperConfig.IsSet(key) {
		return cc.ViperConfig.GetStringSlice(key)
	}
	return viper.GetStringSlice(key)
}

func (cc *ClientConfig) GetStringMap(key string) map[string]interface{} {
	if cc.ViperConfig.IsSet(key) {
		return cc.ViperConfig.GetStringMap(key)
	}
	return viper.GetStringMap(key)
}

// GetReqWithClientConfig injects a client config parsed from a JSON string
// into the request context. Useful for unit testing.
func GetReqWithClientConfig(clientConfig string, req *http.Request) *http.Request {
	v := viper.New()
	v.SetConfigType("json")
	v.ReadConfig(bytes.NewBufferString(clientConfig))
	return req.WithContext(context.WithValue(req.Context(), ClientConfigKey, &ClientConfig{ViperConfig: v}))
}
