package icecast

import "time"

type ReconnectConfig struct {
	Enabled          bool
	InitialBackoffMs int
	MaxBackoffMs     int
}

func (c ReconnectConfig) nextBackoff(attempt int) time.Duration {
	if !c.Enabled {
		return 0
	}
	initial := c.InitialBackoffMs
	if initial <= 0 {
		initial = 1000
	}
	max := c.MaxBackoffMs
	if max <= 0 {
		max = 15000
	}
	maxD := time.Duration(max) * time.Millisecond
	d := time.Duration(initial) * time.Millisecond
	// BUG-E fix: check d <= 0 (overflow) as well as d >= max.
	// int64 overflow after ~63 doublings caused d to go negative,
	// producing spurious short backoffs before recovering.
	for i := 1; i < attempt; i++ {
		d *= 2
		if d <= 0 || d >= maxD {
			return maxD
		}
	}
	return d
}
