<?php
/**
 * Redis Cache Wrapper
 */

declare(strict_types=1);

namespace App\Core;

class Cache
{
    private static ?\Predis\Client $client = null;

    public static function getInstance(): ?\Predis\Client
    {
        if (self::$client === null) {
            $host = env('REDIS_HOST', '127.0.0.1');
            $port = (int)env('REDIS_PORT', 6379);
            $pass = env('REDIS_PASSWORD', null);

            try {
                if (!class_exists('\Predis\Client')) {
                    throw new \Exception('Predis client is not installed. Please run composer install.');
                }
                
                self::$client = new \Predis\Client([
                    'scheme' => 'tcp',
                    'host'   => $host,
                    'port'   => $port,
                    'password' => $pass,
                ]);
                self::$client->connect();
            } catch (\Throwable $e) { // Catch \Throwable instead of \Exception to catch fatal class errors
                error_log("Redis Connection Error: " . $e->getMessage());
                return null;
            }
        }
        return self::$client;
    }

    public static function set(string $key, $value, int $ttl = 3600): bool
    {
        $redis = self::getInstance();
        if (!$redis) return false;

        $redis->setex($key, $ttl, serialize($value));
        return true;
    }

    public static function get(string $key)
    {
        $redis = self::getInstance();
        if (!$redis) return false;

        $data = $redis->get($key);
        return $data ? unserialize($data) : null;
    }

    public static function delete(string $key): void
    {
        $redis = self::getInstance();
        if ($redis) $redis->del([$key]);
    }
}
