<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Components;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\AdminBundle\Form\UserChangePasswordType;
use Ferienpass\CoreBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveAction;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\LiveComponent\ValidatableComponentTrait;

#[AsLiveComponent(route: 'live_component_admin')]
class ChangePassword extends AbstractController
{
    use ComponentWithFormTrait;
    use DefaultActionTrait;
    use ValidatableComponentTrait;

    public string|TranslatableInterface|null $success = null;

    #[LiveAction]
    public function submit(EntityManagerInterface $em, UserPasswordHasherInterface $passwordHasher): void
    {
        $this->submitForm();

        $user = $this->getUser();
        if (!$user instanceof User) {
            return;
        }

        $hashedPassword = $passwordHasher->hashPassword($user, $this->getForm()->get('plainPassword')->getData());
        $user->setPassword($hashedPassword);
        $user->setModifiedAt();

        $em->flush();

        $this->success = new TranslatableMessage('MSC.newPasswordSet', [], 'contao_default');
    }

    protected function instantiateForm(): FormInterface
    {
        return $this->createForm(UserChangePasswordType::class);
    }
}
