package common

import (
	"strconv"
	"time"

	"github.com/tech/sendico/pkg/model"
)

// DurationSetting reads a positive duration override from settings or returns def when the value is missing or invalid.
func DurationSetting(settings model.SettingsT, key string, def time.Duration) time.Duration {
	if settings == nil {
		return def
	}
	value, ok := settings[key]
	if !ok {
		return def
	}

	switch v := value.(type) {
	case time.Duration:
		if v > 0 {
			return v
		}
	case int:
		if v > 0 {
			return time.Duration(v) * time.Second
		}
	case int64:
		if v > 0 {
			return time.Duration(v) * time.Second
		}
	case float64:
		if v > 0 {
			return time.Duration(v * float64(time.Second))
		}
	case string:
		if parsed, err := time.ParseDuration(v); err == nil && parsed > 0 {
			return parsed
		}
		if seconds, err := strconv.ParseFloat(v, 64); err == nil && seconds > 0 {
			return time.Duration(seconds * float64(time.Second))
		}
	}
	return def
}
