// config/config.go
package config

import (
	"fmt"
	"os"

	"github.com/joho/godotenv"
)

type Config struct {
	Port        string
	DatabaseURL string
	StaticURL   string `env:"STATIC_URL" envDefault:"http://localhost:8080"`
	JWTSecret   string `env:"JWT_SECRET,required"`

	// Email configuration
	SMTPHost     string `env:"SMTP_HOST,required"`
	SMTPPort     int    `env:"SMTP_PORT,required"`
	SMTPUsername string `env:"SMTP_USERNAME,required"`
	SMTPPassword string `env:"SMTP_PASSWORD,required"`
	FromEmail    string `env:"FROM_EMAIL,required"`
	FrontendURL  string `env:"FRONTEND_URL,required"`
}

func Load() *Config {
	_ = godotenv.Load(".env")
	port := getEnv("PORT", "8080")
	jwtSecret := getEnv("JWT_SECRET", "your-secret-key")

	// Формируем DSN для PostgreSQL из переменных окружения
	databaseURL := getPostgresDSN()

	return &Config{
		Port:        port,
		DatabaseURL: databaseURL,
		JWTSecret:   jwtSecret,
	}
}

func getPostgresDSN() string {
	host := getEnv("DB_HOST", "localhost")
	port := getEnv("DB_PORT", "5432")
	user := getEnv("DB_USER", "postgres")
	password := getEnv("DB_PASSWORD", "postgres")
	dbname := getEnv("DB_NAME", "bb_db")
	sslmode := getEnv("DB_SSLMODE", "disable")

	return fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
		host, port, user, password, dbname, sslmode)
}

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