<?php

declare(strict_types=1);

namespace CpCreation\AltchaBundle\Command;

use CpCreation\AltchaBundle\Contract\AltchaServiceClientInterface;
use CpCreation\AltchaBundle\Scope\ScopeRegistry;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
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: 'cp-creation:altcha:scopes:sync',
    description: 'Compare or synchronize the Symfony ALTCHA scope manifest.',
)]
final class SynchronizeScopesCommand extends Command
{
    public function __construct(
        private readonly AltchaServiceClientInterface $client,
        private readonly ScopeRegistry $scopeRegistry,
    ) {
        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->addOption('apply', null, InputOption::VALUE_NONE, 'Apply the synchronization.');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $dryRun = !$input->getOption('apply');

        try {
            $result = $this->client->synchronizeScopes($this->scopeRegistry->manifest(), $dryRun);
        } catch (\Throwable $exception) {
            $io->error('ALTCHA scope synchronization failed: '.$exception->getMessage());

            return self::FAILURE;
        }

        $io->title($dryRun ? 'ALTCHA scopes — DRY-RUN' : 'ALTCHA scopes — APPLY');
        $io->definitionList(
            ['Created' => implode(', ', $result->created) ?: '—'],
            ['Updated' => implode(', ', $result->updated) ?: '—'],
            ['Unchanged' => implode(', ', $result->unchanged) ?: '—'],
        );

        return self::SUCCESS;
    }
}
