<?php
/**
 * Clear storage logs 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 LogsClearCommand extends Command
{
    public function getName(): string
    {
        return 'logs:clear';
    }

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

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

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

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

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

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