package config

import (
	"os"
	"strconv"
)

type Config struct {
	DatabaseURL        string
	RedisURL           string
	RedisKeyPrefix     string
	WorkerQueue        string
	Host               string
	Port               int
	SocketPath         string
	ScheduleConfigPath string
	SchedulerEnabled   bool
}

func Load() Config {
	scheduleConfigPath := getenv("ALT_WORKER_SCHEDULE_CONFIG", "")
	return Config{
		DatabaseURL:        getenv("DATABASE_URL", "postgres://alt:alt@localhost:15430/alt?sslmode=disable"),
		RedisURL:           getenv("REDIS_URL", "redis://localhost:16330/0"),
		RedisKeyPrefix:     getenv("ALT_REDIS_KEY_PREFIX", "alt"),
		WorkerQueue:        getenv("ALT_WORKER_QUEUE", "default"),
		Host:               getenv("ALT_WORKER_HOST", "127.0.0.1"),
		Port:               getenvInt("ALT_WORKER_PORT", 18031),
		SocketPath:         getenv("ALT_WORKER_SOCKET_PATH", "/socket"),
		ScheduleConfigPath: scheduleConfigPath,
		SchedulerEnabled:   scheduleConfigPath != "",
	}
}

func getenv(key, fallback string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return fallback
}

func getenvInt(key string, fallback int) int {
	value := os.Getenv(key)
	if value == "" {
		return fallback
	}
	parsed, err := strconv.Atoi(value)
	if err != nil {
		return fallback
	}
	return parsed
}
