package config

import (
	"log"
	"os"
	"strconv"
	"strings"

	"github.com/joho/godotenv"
)

// Config holds all application configuration.
type Config struct {
	DatabaseURL        string
	TelegramBotToken   string
	TelegramAdminIDs   []int64
	ProxyURL           string
	TokenCheckInterval int // minutes
	TeamCapacity       int
	OAuthCallbackPort  int
}

// Load reads configuration from environment variables / .env file.
func Load() *Config {
	_ = godotenv.Load()

	cfg := &Config{
		DatabaseURL:        getEnv("DATABASE_URL", "postgres://postgres:postgres@localhost:5432/teamhelper?sslmode=disable"),
		TelegramBotToken:   getEnv("TELEGRAM_BOT_TOKEN", ""),
		ProxyURL:           getEnv("PROXY_URL", ""),
		TokenCheckInterval: getEnvInt("TOKEN_CHECK_INTERVAL", 30),
		TeamCapacity:       getEnvInt("TEAM_CAPACITY", 6),
		OAuthCallbackPort:  getEnvInt("OAUTH_CALLBACK_PORT", 1455),
	}

	raw := getEnv("TELEGRAM_ADMIN_IDS", "")
	if raw != "" {
		for _, s := range strings.Split(raw, ",") {
			s = strings.TrimSpace(s)
			if s == "" {
				continue
			}
			id, err := strconv.ParseInt(s, 10, 64)
			if err != nil {
				log.Printf("[Config] 无法解析管理员ID '%s': %v", s, err)
				continue
			}
			cfg.TelegramAdminIDs = append(cfg.TelegramAdminIDs, id)
		}
	}

	if cfg.TelegramBotToken == "" {
		log.Fatal("[Config] TELEGRAM_BOT_TOKEN 未配置")
	}

	return cfg
}

// IsAdmin checks if the given Telegram user ID is an admin.
func (c *Config) IsAdmin(userID int64) bool {
	for _, id := range c.TelegramAdminIDs {
		if id == userID {
			return true
		}
	}
	return false
}

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

func getEnvInt(key string, fallback int) int {
	v := os.Getenv(key)
	if v == "" {
		return fallback
	}
	i, err := strconv.Atoi(v)
	if err != nil {
		return fallback
	}
	return i
}
