<?php

declare(strict_types=1);

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

use apexl\Io\includes\System;
use apexl\Io\services\Cache;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(name: 'cache:view', description: 'View an item in the cache')]
class CacheViewCommand extends DaedalusCommand
{
    protected function configure(): void
    {
        $this->addArgument('key', InputArgument::REQUIRED, 'The key to view from the cache');
        $this->addOption('all', 'a', InputOption::VALUE_NONE, 'Display all item information, not just value');
        $this->addOption('stale', 's', InputOption::VALUE_NONE, 'Include stale items');
    }

    /**
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        $cache = System::getRegisteredService(Cache::class);

        $item = $cache->getItem($input->getArgument('key'));
        $value = $item->get();
        if ($value === null || ($item->isMiss() && !$input->getOption('stale'))) {
            $io->error('Item not found');

            return 1;
        }

        $io->success(
            $input->getOption('all') ? json_encode([
                'key' => $item->getKey(),
                'value' => $value,
                'expires' => $item->getExpiration()->format('y-m-d H:i:s'),
                'expired' => $item->isHit() ? 'false' : 'true',
            ], JSON_PRETTY_PRINT) : $value
        );


        return 0;
    }
}
