<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Commands;

use apexl\Io\modules\user\services\ExpiredRefreshTokenPurger;
use app\vendor\apexl\io\src\Io\modules\system\commands\DaedalusCommand;
use Exception;
use Symfony\Component\Console\Attribute\AsCommand;
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: 'user:purge-refresh-tokens',
    description: 'Delete expired refresh tokens (schedule daily)'
)]
class UserPurgeRefreshTokensCommand extends DaedalusCommand
{
    public function __construct(private readonly ExpiredRefreshTokenPurger $purger)
    {
        parent::__construct();
    }

    protected function configure(): void
    {
        parent::configure();

        $this->addOption(
            'grace',
            null,
            InputOption::VALUE_REQUIRED,
            'Seconds to keep a row after it expired',
            (string) ExpiredRefreshTokenPurger::DEFAULT_GRACE_SECONDS,
        );
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);

        try {
            $purged = $this->purger->purge((int) $input->getOption('grace'));

            $io->success(sprintf('Purged %d expired refresh token(s).', $purged));

            return self::SUCCESS;
        } catch (Exception $e) {
            $io->error($e->getMessage());

            return self::FAILURE;
        }
    }
}
