<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Commands;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\modules\user\entities\roleEntity;
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-role', description: 'Assign a role to a user')]
class UserAssignRoleCommand extends AbstractUserCommand
{
    protected function configure(): void
    {
        parent::configure();

        $this->addArgument('userIdOrEmail', InputArgument::REQUIRED, 'The user ID or email');
        $this->addArgument('roleIdOrName', InputArgument::REQUIRED, 'The role ID or name');
    }

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

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

            return self::FAILURE;
        }

        try {
            $role = $this->getRole($roleIdOrName);
        } catch (RecordNotFoundException) {
            $io->error(sprintf('Role with ID or name \'%s\' not found.', $roleIdOrName));

            return self::FAILURE;
        }

        try {
            $user->addRole($role);

            return self::SUCCESS;

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

            return self::FAILURE;
        }
    }

    /**
     * @throws RecordNotFoundException
     */
    private function getRole(mixed $roleIdOrName): roleEntity
    {
        $role = new roleEntity();

        if (is_numeric($roleIdOrName)) {
            $role->load($roleIdOrName);
            if ($role->id === null) {
                throw new RecordNotFoundException();
            }

            return $role;
        }

        $role->loadBy('name', $roleIdOrName);

        return $role;

    }
}
