<?php

declare(strict_types=1);

namespace app\vendor\apexl\io\src\Io\modules\system\commands;

use Apexl\Io\Cache\Interfaces\CacheManagerInterface;
use apexl\Io\services\CacheStream;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'cache:clear', description: 'Remove item(s) from the cache')]
class CacheClearCommand extends DaedalusCommand
{
    public function __construct(private readonly CacheManagerInterface $cacheManager, ?string $name = null)
    {
        parent::__construct($name);
    }

    protected function configure(): void
    {
        $this->addOption('stream', 'S', InputArgument::OPTIONAL, 'The stream to clear', 'default');
        $this->addArgument(
            'key',
            InputArgument::OPTIONAL,
            'The key to clear from the cache.  If empty, all items will be cleared.'
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $stream = $input->getOption('stream');
        $cache = $stream === 'default' ? $this->cacheManager->default() : $this->cacheManager->stream($stream);

        $key = $input->getArgument('key');

        if (!$key) {
            $cache->clear();
            $io->success('Purged all items from the cache');

            return 0;
        }

        $cache->deleteItem($key);
        $io->success(sprintf('Purged \'%s\' from the cache', $key));

        return 0;
    }
}
