package config

import (
	"os"
	"strconv"
)

type Config struct {
	Port           string
	DataDir        string
	StorageDir     string
	JWTSecret      string
	JWTExpirySecs  int
	DBPath         string
	ThumbnailDir   string
	TrashDir       string
	VersionsDir    string
	BackupDir      string
	MaxLoginAttempts int
	LockoutSeconds   int
}

func Load() *Config {
	cfg := &Config{
		Port:             getEnv("PORT", "5827"),
		DataDir:          getEnv("DATA_DIR", "/app/data"),
		StorageDir:       getEnv("STORAGE_DIR", "/storage"),
		JWTSecret:        getEnv("JWT_SECRET", ""),
		JWTExpirySecs:    getEnvInt("JWT_EXPIRY_SECS", 900),       // 15 minutes
		MaxLoginAttempts: getEnvInt("MAX_LOGIN_ATTEMPTS", 5),
		LockoutSeconds:   getEnvInt("LOCKOUT_SECONDS", 300),       // 5 minutes
	}

	cfg.DBPath = cfg.DataDir + "/drive.db"
	cfg.ThumbnailDir = cfg.DataDir + "/thumbnails"
	cfg.TrashDir = cfg.StorageDir + "/.trash"
	cfg.VersionsDir = cfg.StorageDir + "/.versions"
	cfg.BackupDir = cfg.StorageDir + "/.backups"

	return cfg
}

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

func getEnvInt(key string, fallback int) int {
	if value, ok := os.LookupEnv(key); ok {
		if intVal, err := strconv.Atoi(value); err == nil {
			return intVal
		}
	}
	return fallback
}
