<?php

namespace App\Service;

use App\Entity\User;
use App\Exception\UserAlreadyExistsException;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class UserManagementService
{
    public function __construct(
        private UserRepository $userRepository,
        private EntityManagerInterface $em,
        private UserPasswordHasherInterface $passwordHasher,
    ) {
    }

    /**
     * @param string[] $roles
     *
     * @throws UserAlreadyExistsException
     * @throws \Exception
     */
    public function createBaseUser(string $email, string $firstName, string $lastName, array $roles): User
    {
        if ('' === $email || '' === $firstName || '' === $lastName) {
            throw new \InvalidArgumentException('Le prenom, nom et email sont requis.');
        }

        if (null !== $this->userRepository->findOneBy(['email' => $email])) {
            throw new UserAlreadyExistsException();
        }

        $tempPassword = bin2hex(random_bytes(8));

        $user = new User();
        $user->setEmail($email);
        $user->setFirstName($firstName);
        $user->setLastName($lastName);
        $user->setRoles($roles);
        $user->setPassword($this->passwordHasher->hashPassword($user, $tempPassword));
        $user->setTempPassword($tempPassword);

        $this->em->persist($user);

        return $user;
    }
}
