package config

import (
	"os"
	"strconv"
	"time"
)

type Config struct {
	Host     string
	Port     string
	DataPath string
	MaxActivityLogEntries   int
	AdminLogBroadcastLimit  int
	StaleRoomCleanupInterval time.Duration
	StaleRoomTTL             time.Duration
}

func envIntOrDefault(name string, fallback int) int {
	raw := os.Getenv(name)
	if raw == "" {
		return fallback
	}

	parsed, err := strconv.Atoi(raw)
	if err != nil || parsed <= 0 {
		return fallback
	}

	return parsed
}

func envDurationOrDefault(name string, fallback time.Duration) time.Duration {
	raw := os.Getenv(name)
	if raw == "" {
		return fallback
	}

	parsed, err := time.ParseDuration(raw)
	if err != nil || parsed <= 0 {
		return fallback
	}

	return parsed
}

func Load() Config {
	host := os.Getenv("HOST")
	if host == "" {
		host = "0.0.0.0"
	}

	port := os.Getenv("PORT")
	if port == "" {
		port = "8002"
	}

	dataPath := os.Getenv("DATA_PATH")
	if dataPath == "" {
		dataPath = "./data"
	}

	maxActivityLogEntries := envIntOrDefault("MAX_ACTIVITY_LOG_ENTRIES", 400)
	adminLogBroadcastLimit := envIntOrDefault("ADMIN_LOG_BROADCAST_LIMIT", 200)
	staleRoomCleanupInterval := envDurationOrDefault("STALE_ROOM_CLEANUP_INTERVAL", 5*time.Minute)
	staleRoomTTL := envDurationOrDefault("STALE_ROOM_TTL", 30*time.Minute)

	return Config{
		Host:     host,
		Port:     port,
		DataPath: dataPath,
		MaxActivityLogEntries:   maxActivityLogEntries,
		AdminLogBroadcastLimit:  adminLogBroadcastLimit,
		StaleRoomCleanupInterval: staleRoomCleanupInterval,
		StaleRoomTTL:             staleRoomTTL,
	}
}
