<?php
/**
 * Redis singleton — used for rate limiting + OTP cooldowns.
 * Degrades gracefully if Redis is disabled or extension is missing.
 */

declare(strict_types=1);

class Cache
{
    private static ?Redis $instance = null;
    private static bool $tried = false;

    public static function redis(): ?Redis
    {
        if (self::$tried) return self::$instance;
        self::$tried = true;

        if ((int)env('REDIS_ENABLED', 0) !== 1) return null;
        if (!extension_loaded('redis')) {
            Logger::warning('Redis extension not loaded; falling back to no-cache');
            return null;
        }

        try {
            $r = new Redis();
            $r->connect((string)env('REDIS_HOST', '127.0.0.1'), (int)env('REDIS_PORT', 6379), 1.0);
            $pwd = (string)env('REDIS_PASSWORD', '');
            if ($pwd !== '') $r->auth($pwd);
            $prefix = (string)env('REDIS_PREFIX', 'pub:');
            $r->setOption(Redis::OPT_PREFIX, $prefix);
            self::$instance = $r;
        } catch (Throwable $e) {
            Logger::warning('Redis connection failed', ['error' => $e->getMessage()]);
            self::$instance = null;
        }
        return self::$instance;
    }
}

function redis(): ?Redis
{
    return Cache::redis();
}
