package config

import (
	"os"
	"time"
)

type Config struct {
	ServerPort           string
	BotToken             string
	PaymentProviderToken string
	DB                   DBConfig
	Redis                RedisConfig
	Game                 GameConfig
	Admin                AdminConfig
}

type DBConfig struct {
	Host     string
	Port     string
	User     string
	Password string
	Name     string
}

func (c DBConfig) DSN() string {
	return "postgres://" + c.User + ":" + c.Password + "@" + c.Host + ":" + c.Port + "/" + c.Name + "?sslmode=disable"
}

type RedisConfig struct {
	Addr string
}

type GameConfig struct {
	TickRate time.Duration
}

type AdminConfig struct {
	BasicAuthUsername string
	BasicAuthPassword string
	BasicAuthRealm    string
}

func Load() *Config {
	return &Config{
		ServerPort:           envOrDefault("SERVER_PORT", "8080"),
		BotToken:             os.Getenv("BOT_TOKEN"),
		PaymentProviderToken: os.Getenv("PAYMENT_PROVIDER_TOKEN"),
		DB: DBConfig{
			Host:     envOrDefault("DB_HOST", "localhost"),
			Port:     envOrDefault("DB_PORT", "5432"),
			User:     envOrDefault("DB_USER", "autohero"),
			Password: envOrDefault("DB_PASSWORD", "autohero"),
			Name:     envOrDefault("DB_NAME", "autohero"),
		},
		Redis: RedisConfig{
			Addr: envOrDefault("REDIS_ADDR", "localhost:6379"),
		},
		Game: GameConfig{
			TickRate: 100 * time.Millisecond, // 10 ticks per second
		},
		Admin: AdminConfig{
			BasicAuthUsername: os.Getenv("ADMIN_BASIC_AUTH_USERNAME"),
			BasicAuthPassword: os.Getenv("ADMIN_BASIC_AUTH_PASSWORD"),
			BasicAuthRealm:    envOrDefault("ADMIN_BASIC_AUTH_REALM", "AutoHero Admin"),
		},
	}
}

func envOrDefault(key, defaultVal string) string {
	if val := os.Getenv(key); val != "" {
		return val
	}
	return defaultVal
}
