<?php
// Only include the Redis driver
use Vichan\Data\Driver\{CacheDriver, RedisCacheDriver};

defined('TINYBOARD') or exit;


class Cache {
	private static function buildCache(): CacheDriver {
		global $config;
		switch ($config['cache']['enabled']) {
			case 'redis':
				if (!isset($config['cache']['redis'][0], $config['cache']['redis'][1], $config['cache']['redis'][2], $config['cache']['redis'][3])) {
					throw new \RuntimeException('Incomplete Redis configuration.');
				}
				return new RedisCacheDriver(
					$config['cache']['prefix'] ?? '', // Provide default empty prefix if not set
					$config['cache']['redis'][0],
					$config['cache']['redis'][1],
					$config['cache']['redis'][2],
					$config['cache']['redis'][3] 
				);

			default:
				throw new \RuntimeException("Unsupported or invalid cache driver specified: " . ($config['cache']['enabled'] ?? 'Not Set'));
		}
	}

	public static function getCache(): CacheDriver {
		static $cache;
		return $cache ??= self::buildCache();
	}

	public static function get($key) {
		global $config, $debug;

		$ret = self::getCache()->get((string)$key); // Ensure key is string

		$isMiss = ($ret === null);

		if ($config['debug']) {
			$debug['cached'][] = ($config['cache']['prefix'] ?? '') . $key . ($isMiss ? ' (miss)' : ' (hit)');
		}

		return $isMiss ? false : $ret;
	}

	public static function set($key, $value, $expires = false) {
		global $config, $debug;

		if ($expires === false || $expires === null) {
			// Use configured default timeout if no specific expiry is given
			$expires = $config['cache']['timeout'] ?? 3600; // Default to 1 hour if timeout isn't set
		}

		$expires = ($expires !== false) ? max(0, (int)$expires) : false;

		self::getCache()->set((string)$key, $value, $expires);

		if ($config['debug']) {
			$debug['cached'][] = ($config['cache']['prefix'] ?? '') . $key . ' (set)';
		}
	}

	public static function delete($key) {
		global $config, $debug;

		self::getCache()->delete((string)$key);

		if ($config['debug']) {
			$debug['cached'][] = ($config['cache']['prefix'] ?? '') . $key . ' (deleted)';
		}
	}

	public static function flush() {
		self::getCache()->flush();
		return false;
	}
}