package config

import (
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"
)

type Config struct {
	// Server
	Port    string
	GinMode string

	// Database
	DBType     string
	DBHost     string
	DBPort     string
	DBUser     string
	DBPassword string
	DBName     string

	// Redis
	RedisHost     string
	RedisPort     string
	RedisPassword string
	RedisDB       string

	// Auth
	AuthCenterURL      string
	AuthTokenCacheTTL  string
	AllowedOrigins     string

	// Web3
	ArbSepoliaRPC string
	BSCTestnetRPC string

	// Liquidation Bot
	LiquidatorPrivateKey string

	// Collateral Buyer Bot
	CollateralBuyerPrivateKey string
	CollateralBuyerMaxAmount  string
	CollateralBuyerSlippage   int
}

var AppConfig *Config

// Load configuration from environment variables
func Load() *Config {
	// Load .env file
	if err := godotenv.Load(); err != nil {
		log.Println("No .env file found, using environment variables")
	}

	AppConfig = &Config{
		Port:    getEnv("PORT", "8080"),
		GinMode: getEnv("GIN_MODE", "debug"),

		DBType:     getEnv("DB_TYPE", "mysql"),
		DBHost:     getEnv("DB_HOST", "localhost"),
		DBPort:     getEnv("DB_PORT", "3306"),
		DBUser:     getEnv("DB_USER", "root"),
		DBPassword: getEnv("DB_PASSWORD", ""),
		DBName:     getEnv("DB_NAME", "assetx"),

		RedisHost:     getEnv("REDIS_HOST", "localhost"),
		RedisPort:     getEnv("REDIS_PORT", "6379"),
		RedisPassword: getEnv("REDIS_PASSWORD", ""),
		RedisDB:       getEnv("REDIS_DB", "0"),

		AuthCenterURL:     getEnv("AUTH_CENTER_URL", "https://auth.upay01.com"),
		AuthTokenCacheTTL: getEnv("AUTH_TOKEN_CACHE_TTL", "300"),
		AllowedOrigins:    getEnv("ALLOWED_ORIGINS", "http://localhost:8000"),

		ArbSepoliaRPC: getEnv("ARB_SEPOLIA_RPC", "https://sepolia-rollup.arbitrum.io/rpc"),
		BSCTestnetRPC: getEnv("BSC_TESTNET_RPC", "https://api.zan.top/node/v1/bsc/testnet/baf84c429d284bb5b676cb8c9ca21c07"),

		LiquidatorPrivateKey: getEnv("LIQUIDATOR_PRIVATE_KEY", ""),

		CollateralBuyerPrivateKey: getEnv("COLLATERAL_BUYER_PRIVATE_KEY", ""),
		CollateralBuyerMaxAmount:  getEnv("COLLATERAL_BUYER_MAX_AMOUNT", "100"),
		CollateralBuyerSlippage:   getEnvInt("COLLATERAL_BUYER_SLIPPAGE", 2),
	}

	return AppConfig
}

func getEnv(key, defaultValue string) string {
	value := os.Getenv(key)
	if value == "" {
		return defaultValue
	}
	return value
}

func getEnvInt(key string, defaultValue int) int {
	value := os.Getenv(key)
	if value == "" {
		return defaultValue
	}
	var i int
	if _, err := fmt.Sscanf(value, "%d", &i); err != nil {
		return defaultValue
	}
	return i
}
