<?php


namespace Diamond\Modules\AdminUsers;

use ActiveTable\Contracts\CommandInterface;
use Diamond\Application\Notification\Exceptions\NotificationException;
use Diamond\Application\Notification\NotificationService;
use Diamond\Application\User\Exceptions\UserException;
use Diamond\Application\User\UserService;
use Diamond\Domain\User\Contracts\UserEntityInterface;
use Diamond\Helpers\Form;
use Diamond\Repositories\User\UserRepository;

use DiamondTable\CommandException;
use DiamondTable\Commands\CommandAbstract;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;


class ChangePasswordCommand extends CommandAbstract implements CommandInterface
{
    protected $securePolicy;
    protected $request;
    protected $notification;
    protected $userRepository;

    public function __construct(UserService $securePolicy,
                                Request $request,
                                NotificationService $notification,
                                UserRepository $userRepository,
                                private string $redirectUrl)
    {
        $this->securePolicy = $securePolicy;
        $this->request = $request;
        $this->notification = $notification;
        $this->userRepository = $userRepository;
    }


    /**
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Throwable
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function process(): void
    {
        $data = $this->request->request->all();

        $id = (int)input_get('id');

        /**
         * @var UserEntityInterface $user
         */
        if (!$user = $this->userRepository->findById($id)) {
            throw new CommandException(sprintf('Пользователь с №`%s` не найден', $id));
        }

        try {
            $this->securePolicy->changeUserPassword($user->getId(), $data['new_password']);
            $this->addFormNoticeSuccess('Пароль успешно изменен.');
        } catch (UserException $ex) {
            throw new CommandException('При изменении пароля произошла ошибка.');
        }

        if (isset($data['notify']) && $data['notify'] === 'Y') {
            try {
                $dataSnippets = array_change_key_case($user->toArray());
                $dataSnippets['code'] = $data['new_password'];
                $this->notification->sendToEmailByReport('recovery', $user->getEmail(), $dataSnippets);
                $this->addFormNoticeSuccess('Уведомление успешно отправлено');
            } catch (NotificationException $ex) {

                $this->addFormNoticeWarning('При отправке уведомления произошла ошибка');
            }
        }

        $this->redirect();
    }

}