<?php
/**
 * Clear storage cache files.
 *
 * @package Flowaxy\Interface\CLI\Commands
 */

declare(strict_types=1);

namespace Flowaxy\Interface\CLI\Commands;

use Flowaxy\Core\System\PathResolver;
use Flowaxy\Interface\CLI\Command;

use function is_dir;
use function is_file;
use function scandir;
use function unlink;

final class CacheClearCommand extends Command
{
    public function getName(): string
    {
        return 'cache:clear';
    }

    public function getDescription(): string
    {
        return 'Clear storage/cache (keeps .htaccess)';
    }

    public function getHelp(): string
    {
        return "Usage:\n"
            . "  php index.php cache:clear\n";
    }

    protected function handle(array $args): int
    {
        $cacheDir = PathResolver::cache();
        if (!is_dir($cacheDir)) {
            $this->error("Cache directory not found: {$cacheDir}");
            return 1;
        }

        $deleted = 0;
        $entries = scandir($cacheDir);
        if ($entries === false) {
            $this->error("Failed to read directory: {$cacheDir}");
            return 1;
        }

        foreach ($entries as $entry) {
            if ($entry === '.' || $entry === '..' || $entry === '.htaccess') {
                continue;
            }
            $path = $cacheDir . DS . $entry;
            if (is_file($path)) {
                if (@unlink($path)) {
                    $deleted++;
                }
            }
        }

        $this->output("OK: cache cleared ({$deleted} file(s) deleted).");
        return 0;
    }
}
