// Package common provides shared market connector utilities.
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.
//
//nolint:cyclop
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 val := value.(type) {
	case time.Duration:
		if val > 0 {
			return val
		}
	case int:
		if val > 0 {
			return time.Duration(val) * time.Second
		}
	case int64:
		if val > 0 {
			return time.Duration(val) * time.Second
		}
	case float64:
		if val > 0 {
			return time.Duration(val * float64(time.Second))
		}
	case string:
		parsed, parseErr := time.ParseDuration(val)
		if parseErr == nil && parsed > 0 {
			return parsed
		}

		seconds, floatErr := strconv.ParseFloat(val, 64)
		if floatErr == nil && seconds > 0 {
			return time.Duration(seconds * float64(time.Second))
		}
	}

	return def
}
