<?php
/**
 * Command to update entity URLs
 */
namespace Autogedal\UrlUpdater\Console\Command;

use Autogedal\UrlUpdater\Model\UrlUpdater;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class UpdateUrl extends Command
{
    /**
     * Command option constants
     */
    const ENTITY_TYPE = 'entity-type';
    const ENTITY_ID = 'entity-id';
    const NEW_URL = 'new-url';

    /**
     * @var UrlUpdater
     */
    private $urlUpdater;

    /**
     * @var State
     */
    private $appState;

    /**
     * Constructor
     *
     * @param UrlUpdater $urlUpdater
     * @param State $appState
     * @param string|null $name
     */
    public function __construct(
        UrlUpdater $urlUpdater,
        State $appState,
        ?string $name = null
    ) {
        parent::__construct($name);
        $this->urlUpdater = $urlUpdater;
        $this->appState = $appState;
    }

    /**
     * Configure command
     *
     * @return void
     */
    protected function configure()
    {
        $this->setName('autogedal:url:update')
            ->setDescription('Update URL for a product or category')
            ->setDefinition([
                new InputOption(
                    self::ENTITY_TYPE,
                    null,
                    InputOption::VALUE_REQUIRED,
                    'Entity type (product or category)'
                ),
                new InputOption(
                    self::ENTITY_ID,
                    null,
                    InputOption::VALUE_REQUIRED,
                    'Entity ID'
                ),
                new InputOption(
                    self::NEW_URL,
                    null,
                    InputOption::VALUE_REQUIRED,
                    'New URL key'
                )
            ]);

        parent::configure();
    }

    /**
     * Execute command
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            // Set area code to adminhtml to ensure all functionality works
            try {
                $this->appState->setAreaCode(\Magento\Framework\App\Area::AREA_ADMINHTML);
            } catch (LocalizedException $e) {
                // Area is already set
            }

            $entityType = $input->getOption(self::ENTITY_TYPE);
            $entityId = (int)$input->getOption(self::ENTITY_ID);
            $newUrl = $input->getOption(self::NEW_URL);

            // Validate input
            if (!$entityType || !in_array($entityType, ['product', 'category'])) {
                $output->writeln('<error>Entity type must be "product" or "category"</error>');
                return Command::FAILURE;
            }

            if (!$entityId) {
                $output->writeln('<error>Entity ID is required</error>');
                return Command::FAILURE;
            }

            if (!$newUrl) {
                $output->writeln('<error>New URL is required</error>');
                return Command::FAILURE;
            }

            // Update URL
            $this->urlUpdater->updateUrl($entityType, $entityId, $newUrl);

            $output->writeln(
                "<info>Successfully updated URL for {$entityType} with ID {$entityId} to \"{$newUrl}\"</info>"
            );

            return Command::SUCCESS;
        } catch (\Exception $e) {
            $output->writeln("<error>{$e->getMessage()}</error>");

            if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
                $output->writeln($e->getTraceAsString());
            }

            return Command::FAILURE;
        }
    }
}