<?php

namespace NoahVet\Reef\Command;

use NoahVet\Reef\Factory\ClientFactory;
use NoahVet\Reef\Iam\Client;
use NoahVet\Reef\Security\IAM\Finder\ResourceFinderManager;
use NoahVet\Reef\Security\IAM\Generator\IAMResourceGenerator;
use NoahVet\Reef\Security\IAM\ResourceManager;
use NoahVet\Reef\Security\IAM\ResourceManagerFactory;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SyncResourcesCommand extends Command
{
    protected ?string $reefServiceToken;

    protected IAMResourceGenerator $resourceGenerator;

    protected ResourceFinderManager $resourceFinderManager;

    protected ResourceManager $resourceManager;

    public function __construct(
        ?string $reefServiceToken,
        ClientFactory $clientFactory,
        IAMResourceGenerator $resourceGenerator,
        ResourceFinderManager $resourceFinderManager,
        ResourceManagerFactory $resourceManagerFactory,
    ) {
        parent::__construct('reef:resources:sync');

        $this->reefServiceToken = $reefServiceToken;
        $this->resourceGenerator = $resourceGenerator;
        $this->resourceFinderManager = $resourceFinderManager;
        $this->resourceManager = $resourceManagerFactory->create(
            $clientFactory->createClient($reefServiceToken ?? '', Client::class),
        );
    }

    #[\Override]
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        if (null === $this->reefServiceToken || empty($this->reefServiceToken)) {
            $output->writeln('No service token configured');

            return 1;
        }

        $resourceIterator = $this->resourceFinderManager->createIterator();

        foreach ($resourceIterator->iterate() as $internalResource) {
            $iamResources = $this->resourceGenerator->generate($internalResource);

            foreach ($iamResources as $iamResource) {
                $output->writeln(' - '.(string) $iamResource, OutputInterface::VERBOSITY_VERBOSE);
                $this->resourceManager->register($iamResource);
            }
        }

        return 0;
    }
}
