<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Commands;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\modules\user\interfaces\PermissionInterface;
use Exception;
use Symfony\Component\Console\Attribute\AsCommand;
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: 'user:assign-permission', description: 'Assign a permission to a user')]
class UserAssignPermissionCommand extends AbstractUserCommand
{
    protected function configure(): void
    {
        parent::configure();

        $this->addArgument('userIdOrEmail', InputArgument::REQUIRED, 'The user ID or email');
        $this->addArgument('permission', InputArgument::REQUIRED, 'The fully-qualified Enum permission');
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $userIdOrEmail = $input->getArgument('userIdOrEmail');
        $permission = $input->getArgument('permission');

        try {
            $user = $this->getUser($userIdOrEmail);
        } catch (RecordNotFoundException) {
            $io->error(sprintf('User with ID or email \'%s\' not found.', $userIdOrEmail));

            return self::FAILURE;
        }

        try {
            $permission = $this->getPermission($permission);
        } catch (RecordNotFoundException) {
            $io->error(sprintf('Invalid permission \'%s\'.', $permission));

            return self::FAILURE;
        }

        try {
            $user->addPermission($permission);

            return self::SUCCESS;

        } catch (Exception $e) {
            $io->error($e->getMessage());

            return self::FAILURE;
        }
    }

    /**
     * @throws RecordNotFoundException
     */
    private function getPermission(string $permission): PermissionInterface
    {
        if (!defined($permission)) {
            throw new RecordNotFoundException();
        }

        $permission = constant($permission);

        if (!$permission instanceof PermissionInterface) {
            throw new RecordNotFoundException();
        }

        return $permission;
    }
}
