package retryer

import (
	"context"
	"fmt"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
)

func MakeWithRetry(ctx context.Context, fn func() error, retryer aws.RetryerV2) (err error) {
	var attemptNum int

	maxAttempts := retryer.MaxAttempts()

	for {
		attemptNum++

		err = fn()

		if !retryer.IsErrorRetryable(err) {
			return err
		}

		if attemptNum >= maxAttempts {
			return fmt.Errorf("max retry attempts exausted, max %d: %w", maxAttempts, err)
		}

		retryDelay, reqErr := retryer.RetryDelay(attemptNum, err)
		if reqErr != nil {
			return reqErr
		}

		if reqErr = sleepWithContext(ctx, retryDelay); reqErr != nil {
			return reqErr
		}
	}
}

func sleepWithContext(ctx context.Context, dur time.Duration) error {
	t := time.NewTimer(dur)
	defer t.Stop()

	select {
	case <-t.C:
		break
	case <-ctx.Done():
		return ctx.Err()
	}

	return nil
}