package config

import (
	"log"
	"os"
	"strconv"

	"github.com/joho/godotenv"
)

type Config struct {
	AppEnv              string
	AppPort             string
	DBDsn               string
	JwtAccessSecret     string
	JwtRefreshSecret    string
	JwtAccessTTLMinutes int
	JwtRefreshTTLDays   int
}

func LoadConfig() *Config {
	err := godotenv.Load()
	if err != nil {
		log.Println("Warning: .env file not found")
	}

	return &Config{
		AppEnv:              getEnv("APP_ENV", "dev"),
		AppPort:             getEnv("APP_PORT", "8080"),
		DBDsn:               getEnv("DB_DSN", ""),
		JwtAccessSecret:     getEnv("JWT_ACCESS_SECRET", "secret"),
		JwtRefreshSecret:    getEnv("JWT_REFRESH_SECRET", "refresh_secret"),
		JwtAccessTTLMinutes: getEnvAsInt("JWT_ACCESS_TTL_MINUTES", 15),
		JwtRefreshTTLDays:   getEnvAsInt("JWT_REFRESH_TTL_DAYS", 30),
	}
}

func getEnv(key, fallback string) string {
	if value, ok := os.LookupEnv(key); ok {
		return value
	}
	return fallback
}

func getEnvAsInt(key string, fallback int) int {
	strValue := getEnv(key, "")
	if value, err := strconv.Atoi(strValue); err == nil {
		return value
	}
	return fallback
}
