<?php

namespace App\Framework\Cache;

use App\Framework\Filesystem\FileStorage;
use App\Framework\Filesystem\Storage;

final readonly class FileCacheCleaner
{
    public function __construct(
        private Storage $fileSystem = new FileStorage(),
        private string           $cacheFolder = __DIR__.'/storage/cache/'
    ) {}

    /**
     * Löscht alle abgelaufenen Cache-Dateien im Cache-Verzeichnis.
     * Rückgabe: Anzahl gelöschter Dateien
     */
    public function clean(): int
    {
        $now = time();
        $deleted = 0;
        // Alle passenden Cache-Files suchen (z.B. abcdef12345_1717000000.cache.php)
        foreach ($this->fileSystem->listDirectory($this->cacheFolder, '*.cache.php') as $file) {
            // Expires-At aus Dateiname extrahieren
            if (preg_match('/_(\d+)\.cache\.php$/', $file, $match)) {
                $expiresAt = (int)$match[1];
                if ($expiresAt > 0 && $expiresAt < $now) {
                    if ($this->fileSystem->delete($file) === null) {
                        $deleted++;
                    }
                }
            }
        }
        return $deleted;
    }

}
