package config

import (
	"os"
	"strconv"
)

type Config struct {
	HTTPAddr            string
	DBDriver            string
	DBURL               string
	AppSecret           string
	LogLevel            string
	QCBaseURL           string
	QCToken             string
	PollIntervalSeconds int
	PollTimeoutSeconds  int
	PollMaxConcurrent   int
}

func Load() Config {
	return Config{
		HTTPAddr:            getenv("HTTP_ADDR", ":8080"),
		DBDriver:            getenv("DB_DRIVER", "sqlite"),
		DBURL:               getenv("DB_URL", "data/qctextbuilder.db"),
		AppSecret:           os.Getenv("APP_SECRET"),
		LogLevel:            getenv("LOG_LEVEL", "info"),
		QCBaseURL:           getenv("QC_BASE_URL", "https://qc-api.yggdrasil.dev-mono.net/api/v1"),
		QCToken:             os.Getenv("QC_TOKEN"),
		PollIntervalSeconds: getenvInt("POLL_INTERVAL_SECONDS", 5),
		PollTimeoutSeconds:  getenvInt("POLL_TIMEOUT_SECONDS", 300),
		PollMaxConcurrent:   getenvInt("POLL_MAX_CONCURRENT", 4),
	}
}

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

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