package pgconfig

import (
	"fmt"
	"os"
	"strconv"
	"time"
)

type DatabaseConfig struct {
	DatabaseURL     string
	Host            string
	Port            int
	User            string
	Password        string
	Database        string
	SSLMode         string
	MaxConnections  int
	MaxIdleTime     time.Duration
	ConnMaxLifetime time.Duration
}

func LoadDatabaseConfig() *DatabaseConfig {
	maxConns, _ := strconv.Atoi(getEnv("DB_MAX_CONNECTIONS", "25"))
	maxIdle, _ := time.ParseDuration(getEnv("DB_MAX_IDLE_TIME", "5m"))
	maxLifetime, _ := time.ParseDuration(getEnv("DB_CONN_MAX_LIFETIME", "1h"))
	return &DatabaseConfig{
		DatabaseURL: getEnv("DATABASE_URL", ""),
		Host:        getEnv("DB_HOST", "localhost"), Port: getIntEnv("DB_PORT", 5432),
		User: getEnv("DB_USER", "explorer"), Password: getEnv("DB_PASSWORD", ""),
		Database: getEnv("DB_NAME", "explorer"), SSLMode: getEnv("DB_SSLMODE", "disable"),
		MaxConnections: maxConns, MaxIdleTime: maxIdle, ConnMaxLifetime: maxLifetime,
	}
}

func (c *DatabaseConfig) ConnectionString() string {
	if c.DatabaseURL != "" {
		return c.DatabaseURL
	}
	return fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
		c.Host, c.Port, c.User, c.Password, c.Database, c.SSLMode)
}

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

func getIntEnv(k string, d int) int {
	if v := os.Getenv(k); v != "" {
		if i, err := strconv.Atoi(v); err == nil {
			return i
		}
	}
	return d
}
