<?php

namespace Api\CommandHandler\User;

use Api\Command\User\RegisterUserCommand;
use Api\Domain\Repository\UserRepository;
use Api\Entity\User;

final class RegisterUserHandler
{
    const MINIMUM_LENGHT = 12;
    
    private $repository;
    
    public function __construct (UserRepository $repository)
    {
        $this->repository = $repository;   
    }
    
    public function __invoke(RegisterUserCommand $command)
    {
        $email = $command->email();
        $password = $command->password();
        
        $this->checkEmail();
        $this->checkPassword();
        
        $user = new User($email, $password);
        $this->repository->save($user);
    }
    
    private function checkEmail($email)
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new \Exception('Invalid email');
        }
        
        if ($this->repository->userExists($email)) {
            throw new \Exception('User already exist');
        }
    }
    
    private function checkPassword($password)
    {
        if (self::MINIMUM_LENGHT > strlen($password)) {
            throw new \Exception('Password too short');
        }
    }
}