package tidbcluster

import (
	"math/rand"
	"time"

	"github.com/pingcap/test-infra/sdk/resource"
)

// RandomScale implements util.DoUndo, you can use this struct
// and util.RunPeriodically to introduce randomness into your scaling procedure.
type tiDBClusterRandomScale struct {
	minReplicas uint32
	maxReplicas uint32
	target      resource.TiDBCompType
	timeout     time.Duration

	tc resource.TiDBCluster
}

// RandomScale randomly scales target of tc to [minReplicas, maxReplicas].
func RandomScale(tc resource.TiDBCluster, target resource.TiDBCompType, minReplicas uint32, maxReplicas uint32, timeout time.Duration) *tiDBClusterRandomScale {
	return &tiDBClusterRandomScale{
		minReplicas: minReplicas,
		maxReplicas: maxReplicas,
		target:      target,
		timeout:     timeout,
		tc:          tc,
	}
}

func (t *tiDBClusterRandomScale) Do() error {
	return t.tc.Scale(resource.TiDBClusterScaleOptions{
		Target:   t.target,
		Replicas: uint32(rand.Intn(int(t.maxReplicas-t.minReplicas+1))) + t.minReplicas,
		Timeout:  t.timeout,
	})
}

func (t *tiDBClusterRandomScale) Undo() error { /* nothing need to be done */ return nil }
