<?php

namespace AutoAdmin\Bundle\BrickBuilder\Command;

use AutoAdmin\Bundle\Admin\Router\AdminRouter;
use AutoAdmin\Bundle\BrickBuilder\Helper\BrickResolver;
use AutoAdmin\Bundle\Content\Model\TranslatableInterface;
use AutoAdmin\Bundle\Content\Site\SiteContextHelper;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'aa:content:brick-resolve',
    description: 'Find parent content containing given brick id',
    hidden: false
)]
class BrickResolveCommand extends Command
{
    public function __construct(
        protected BrickResolver $brickResolver,
        protected AdminRouter $adminRouter,
        protected SiteContextHelper $contextHelper,
    ) {
        parent::__construct();
    }

    protected function configure()
    {
        $this->addArgument('brickId', InputArgument::OPTIONAL, 'integer brick id');
    }

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

        $brickId = $input->getArgument('brickId');
        $parentContent = $this->brickResolver->resolve((int)$brickId);

        if (!empty($parentContent)) {
            $io->success('Parent content found');
            $io->writeln('Class: '.get_class($parentContent));
            $io->writeln('Id: '.$parentContent->getId());
            if ($parentContent instanceof TranslatableInterface) {
                $locale = $parentContent->getCurrentTranslation()->getLocale();
                $io->writeln('Locale: '.$locale->getCode().'#'.$locale->getId());
                $url = $this->adminRouter->generate($parentContent, 'update', [
                    '_admin_locale' => $locale->getCode(),
                ]);
                $domain = $this->contextHelper->getDomainByLocale($parentContent->getSite(), $locale);
                // keep http for now, site should implement https redirection by default, thus making this link work in both contexts
                $scheme = 'http';
                $io->writeln('Admin url: '.$scheme.'://'.$domain->getDomain().$url);
            }

        } else {
            $io->error('Could not find any matching content.');
        }

        return Command::SUCCESS;
    }
}
