<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\User;

use CpCreation\VitiCore\User\Model\User;
use CpCreation\VitiCore\User\Repository\ImportedClientGroupRepository;

final readonly class ImportedClientGroupAssigner
{
    public function __construct(
        private ImportedClientGroupRepository $importedClientGroupRepository,
    ) {}

    public function assignTo(User $user): bool
    {
        $email = $user->getEmail();
        if (null === $email || '' === $email) {
            return false;
        }

        $importedClient = $this->importedClientGroupRepository->findOneByEmail($email);
        if (null === $importedClient || !$importedClient->shouldApplyOnRegistration()) {
            return false;
        }

        $user->setGroup($importedClient->getGroup());

        return true;
    }
}
