<?php

namespace App\Commands;

use App\Repository\Organization\OrganizationRepository;
use App\Service\Typo3\SubdomainService;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Exception\InvalidArgumentException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(
    name: 'ot:subdomain:add',
    description: 'Add a subdomain to the given organization and make it the active one'
)]
class AddSubdomainCommand extends Command
{
    public function __construct(
        private readonly OrganizationRepository $organizationRepository,
        private readonly SubdomainService $subdomainService
    ) {
        parent::__construct();
    }

    /**
     * @return void
     */
    protected function configure(): void
    {
        $this->addArgument('organization-id', InputArgument::REQUIRED, 'Id of the organization');
        $this->addArgument('subdomain', InputArgument::REQUIRED, 'The new active subdomain');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $organizationId = $input->getArgument('organization-id');
        if (!is_numeric($organizationId)) {
            throw new InvalidArgumentException('Invalid organization id : ' . $organizationId);
        }
        $organization = $this->organizationRepository->find((int)$organizationId);

        $subdomainValue = $input->getArgument('subdomain');

        $output->writeln("Setting up a new subdomain for organization " . $organizationId . " : " . $subdomainValue);

        $this->subdomainService->addNewSubdomain($organization, $subdomainValue, true);

        $output->writeln("New subdomain added and activated");
        return Command::SUCCESS;
    }
}
