<?php

namespace App\Actions\Support;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Throwable;

/**
 * Shared flood-limiting helper for the legacy public API endpoints.
 *
 * The legacy PHP endpoints used a file-backed limiter that failed OPEN when
 * its storage was unwritable — a lost customer enquiry was considered worse
 * than an occasional spare submission slipping through. This trait preserves
 * that behaviour: any failure reading/writing the rate limiter backend is
 * logged and treated as "not rate limited" rather than surfacing a 500.
 */
trait InteractsWithFloodLimiting
{
    /**
     * Register one attempt against the given bucket, returning whether the
     * request is allowed to proceed (true) or should be rejected (false).
     */
    protected function attempt(string $key, int $maxAttempts, int $decaySeconds = 3600): bool
    {
        try {
            return RateLimiter::attempt($key, $maxAttempts, static fn (): bool => true, $decaySeconds);
        } catch (Throwable $e) {
            Log::warning('Rate limiter backend unavailable; failing open', [
                'key' => $key,
                'exception' => $e->getMessage(),
            ]);

            return true;
        }
    }
}
