package config

import (
	"os"
	"strings"
	"time"
)

// Config 只承载 luck-gateway 自己启动所需的边界配置；业务规则仍由 lucky gift owner service 决策。
type Config struct {
	HTTPAddr          string
	LuckyGiftGRPCAddr string
	AllowedApps       map[string]struct{}
	RequestTimeout    time.Duration
}

func Default() Config {
	return Config{
		HTTPAddr:          envDefault("LUCK_GATEWAY_HTTP_ADDR", ":13014"),
		LuckyGiftGRPCAddr: envDefault("LUCKY_GIFT_GRPC_ADDR", "127.0.0.1:13013"),
		AllowedApps:       parseAllowedApps(envDefault("LUCK_GATEWAY_ALLOWED_APPS", "aslan,yumi")),
		RequestTimeout:    3 * time.Second,
	}
}

func parseAllowedApps(raw string) map[string]struct{} {
	apps := map[string]struct{}{}
	for _, entry := range strings.Split(raw, ",") {
		app := normalizeAppCode(entry)
		if app == "" {
			continue
		}
		apps[app] = struct{}{}
	}
	return apps
}

func normalizeAppCode(value string) string {
	return strings.ToLower(strings.TrimSpace(value))
}

func envDefault(key string, fallback string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return fallback
}
