package settings

import (
	"strconv"
	"strings"

	"github.com/prism/proxy/internal/geodata"
)

// Display merges stored settings with effective defaults for the settings UI.
func Display(raw map[string]string) map[string]string {
	out := make(map[string]string, len(raw)+8)
	for k, v := range raw {
		out[k] = v
	}
	applyGeoDisplayDefaults(out)
	applyScalarDisplayDefaults(out)
	applyLocaleDisplayDefaults(out)
	return out
}

// NormalizeSubmit clears values that match built-in defaults so empty means default.
func NormalizeSubmit(req map[string]string) {
	normalizeGeoSubmit(req)
	normalizeLocaleSubmit(req)
}

func applyGeoDisplayDefaults(out map[string]string) {
	def := geodata.DefaultConfig()
	if strings.TrimSpace(out["geo_country_mmdb_url"]) == "" {
		out["geo_country_mmdb_url"] = def.CountryMmdbURL
	}
	if strings.TrimSpace(out["geo_geoip_url"]) == "" {
		out["geo_geoip_url"] = def.GeoIPURL
	}
	if strings.TrimSpace(out["geo_geosite_url"]) == "" {
		out["geo_geosite_url"] = def.GeoSiteURL
	}
}

func normalizeGeoSubmit(req map[string]string) {
	def := geodata.DefaultConfig()
	if strings.TrimSpace(req["geo_country_mmdb_url"]) == def.CountryMmdbURL {
		req["geo_country_mmdb_url"] = ""
	}
	if strings.TrimSpace(req["geo_geoip_url"]) == def.GeoIPURL {
		req["geo_geoip_url"] = ""
	}
	if strings.TrimSpace(req["geo_geosite_url"]) == def.GeoSiteURL {
		req["geo_geosite_url"] = ""
	}
}

func applyScalarDisplayDefaults(out map[string]string) {
	if strings.TrimSpace(out["login_max_attempts"]) == "" {
		out["login_max_attempts"] = strconv.Itoa(5)
	}
	if strings.TrimSpace(out["login_lock_minutes"]) == "" {
		out["login_lock_minutes"] = strconv.Itoa(15)
	}
}
