package core

import (
	"context"

	"golang.org/x/time/rate"
)

// RateLimiter throttles outbound calls to the target API to
// `Config.RateLimit` requests/second (REQ-2.3.3), wrapping
// `golang.org/x/time/rate`'s token bucket — the Go team's own extended
// stdlib rate limiter, the natural "already-solved dependency" choice
// here.
type RateLimiter struct {
	limiter *rate.Limiter
}

// NewRateLimiter builds a limiter allowing requestsPerSecond sustained,
// with a burst of the same size.
func NewRateLimiter(requestsPerSecond int) *RateLimiter {
	return &RateLimiter{limiter: rate.NewLimiter(rate.Limit(requestsPerSecond), requestsPerSecond)}
}

// Allow reports whether a request may proceed right now, consuming a
// token if so — the non-blocking check the API client uses to fail fast
// with a RateLimitExceededError instead of queueing.
func (r *RateLimiter) Allow() bool {
	return r.limiter.Allow()
}

// Wait blocks until a token is available or ctx is done.
func (r *RateLimiter) Wait(ctx context.Context) error {
	return r.limiter.Wait(ctx)
}
