<?php
declare(strict_types=1);

namespace App\Security;

use Throwable;

/**
 * Picks Redis when configured and available, otherwise falls back to files.
 */
final class RateLimiterFactory
{
    public static function create(array $config, string $fileStorageDir): RateLimiterInterface
    {
        $driver = strtolower(trim((string)($config['driver'] ?? 'auto')));
        $redisConfig = is_array($config['redis'] ?? null) ? (array)$config['redis'] : [];

        if (in_array($driver, ['redis', 'auto'], true)) {
            try {
                if (RedisRateLimiter::isAvailable($redisConfig)) {
                    return new RedisRateLimiter($redisConfig);
                }
            } catch (Throwable $e) {
                if ($driver === 'redis') {
                    // Explicit Redis mode still falls back to files to avoid
                    // breaking existing login/API flows.
                }
            }
        }

        return new FileRateLimiter($fileStorageDir);
    }
}
