<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Sylius\Bundle\ApiBundle\CommandHandler;

use Sylius\Bundle\ApiBundle\Command\ChangeShopUserPassword;
use Sylius\Component\Core\Model\ShopUserInterface;
use Sylius\Component\User\Repository\UserRepositoryInterface;
use Sylius\Component\User\Security\PasswordUpdaterInterface;
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
use Webmozart\Assert\Assert;

/** @experimental */
final class ChangeShopUserPasswordHandler implements MessageHandlerInterface
{
    /** @var PasswordUpdaterInterface */
    private $passwordUpdater;

    /** @var UserRepositoryInterface */
    private $userRepository;

    public function __construct(PasswordUpdaterInterface $passwordUpdater, UserRepositoryInterface $userRepository)
    {
        $this->passwordUpdater = $passwordUpdater;
        $this->userRepository = $userRepository;
    }

    public function __invoke(ChangeShopUserPassword $changeShopUserPassword)
    {
        if ($changeShopUserPassword->confirmNewPassword !== $changeShopUserPassword->newPassword) {
            throw new \InvalidArgumentException('Passwords do not match.');
        }

        /** @var ShopUserInterface|null $user */
        $user = $this->userRepository->find($changeShopUserPassword->getShopUserId());

        Assert::notNull($user);

        $user->setPlainPassword($changeShopUserPassword->newPassword);

        $this->passwordUpdater->updatePassword($user);
    }
}
