<?php
/**
 * Tag Markers Service
 *
 * Manages cache tag timestamps for stale-while-revalidate validation.
 * Enables efficient cache invalidation by tracking when tags were last bumped.
 *
 * @package Mamba\Modules\Caching\Services
 * @since   1.0.0
 */

namespace Mamba\Modules\Caching\Services;

use Mamba\Support\CacheAdapter;

/**
 * Class TagMarkers
 *
 * Tracks tag timestamps to determine if cached content is stale
 * based on when related content was last modified.
 *
 * @since 1.0.0
 */
final class TagMarkers {
    
    public static function bump(string $type, string $id): bool {
        $key = "{$type}-{$id}";
        return CacheAdapter::set($key, time(), 'mamba_tags', 30 * DAY_IN_SECONDS);
    }
    
    public static function getTimestamp(string $type, string $id): int {
        $key = "{$type}-{$id}";
        $timestamp = CacheAdapter::get($key, 'mamba_tags');
        return $timestamp ? (int)$timestamp : 0;
    }
    
    public static function isStale(array $tags, int $fileTime): bool {
        foreach ($tags as $tag) {
            $parts = explode('_', $tag, 2);
            if (count($parts) === 2) {
                $markerTime = self::getTimestamp($parts[0], $parts[1]);
                if ($markerTime > $fileTime) {
                    return true;
                }
            }
        }
        return false;
    }
    
    public static function clear(): void {
        // Use universal cache adapter to clear group
        CacheAdapter::clearGroup('mamba_tags');
    }
    
    // Note: Garbage collection is handled automatically by CacheAdapter TTL
    // No filesystem operations needed as tag markers are stored in object cache with TTL
    

}
