<?php
namespace Stub;
use Model\Athlete;

use Model\CoachAthlete;
use Model\User;
use Repository\IUserRepository;
use Shared\Exception\NotImplementedException;
use Network\IAuthService;
use Shared\IHashPassword;
use Stub\UserRepository;
class AuthService implements IAuthService {
    private IUserRepository $userRepository;
    private IHashPassword $passwordHacher;
    private ?User $currentUser;

    public function __construct(UserRepository $userRepository, IHashPassword $passwordHacher) {
        $this->userRepository = $userRepository;
        $this->passwordHacher = $passwordHacher;
    }

    public function login(string $emailUser,string $password): bool {
        $user = $this->userRepository->getItemByEmail($emailUser);
        if (!$user instanceof User) {
            throw new \Exception('Unable to find user with that name');
        }
        if ($user->isValidPassword($password)) {
            $this->currentUser = $user;
            return true;
        }
        return false;
    }
    public function register(string $username, string $password, $data): bool
    {
    
        $hashedPassword = $this->passwordHacher->hashPassword($password);
    
        $existingUser = $this->userRepository->getItemByEmail($username);
        if ($existingUser != null || $existingUser instanceof User ) {
            throw new \Exception('User already exists');
        }

        $username = $data['username'];
        $prenom = $data['prenom'];
        $username = $data['username'];
        $nom = $data['nom'];
        $email = $data['email'];
        $sexe = $data['sexe'];
        $taille = $data['taille'];
        $poids = $data['poids'];
        $dateNaissance = $data['dateNaissance'] ;
        $roleName = $data['roleName'];
        $role = null;
        if($roleName == "Coach"){
            $role = new CoachAthlete();
        }
        else if($roleName == "Athlete"){
            $role = new Athlete();
        }
        $user = new User(
            random_int(0, 100),
            $nom,
            $prenom,
            $username,
            $email,
            $hashedPassword,
            $sexe,
            $taille,
            $poids,
            $dateNaissance,
            //should use reflexion
            $role
        );
        $this->userRepository->addItem($user);
        $this->currentUser = $user;
        return true;
    }


    public function logoutUser(): bool
    {
        $this->currentUser = null;
        return true;

    }

    public function getCurrentUser(): ?User
    {
        return $this->currentUser;
    }
}