package userbehavior

import (
	"slices"
	"strings"

	ubent "github.com/tidbcloud/devops/entity/userbehavior"
)

// matchGeoSelectors returns whether the given (region/country) matches any selector.
//
// Selectors follow the same semantics as DispatchUBEvents RegionSelectors:
// - region: na/apac/emea/jp (also accept "japan" as alias for "jp")
// - country: ISO 3166-1 alpha-2 country code, compared case-insensitively
func matchGeoSelectors(selectors []string, bizRegion string, country string) (matched bool, matchType string) {
	if len(selectors) == 0 {
		return false, ""
	}

	normalized := make([]string, 0, len(selectors))
	for _, s := range selectors {
		s = strings.ToLower(strings.TrimSpace(s))
		if s == "" {
			continue
		}
		if s == "japan" {
			s = "jp"
		}
		normalized = append(normalized, s)
	}
	if len(normalized) == 0 {
		return false, ""
	}

	regionSel := string(ubent.ToRegionSelectorTp(strings.ToLower(strings.TrimSpace(bizRegion))))
	if regionSel != "" && slices.Contains(normalized, regionSel) {
		return true, "region"
	}

	countrySel := strings.ToLower(strings.TrimSpace(country))
	if countrySel != "" && slices.Contains(normalized, countrySel) {
		return true, "country"
	}

	return false, ""
}

func (s *svc) shouldSkipGTMEmailForGeo(bizRegion string, country string) (bool, string) {
	return matchGeoSelectors(s.conf.GTM.EmailDisabledGeoSelectors, bizRegion, country)
}
