<?php
namespace Data\Core;

use Model\User;
use Model\Athlete;
use Model\CoachAthlete;
use Repository\IUserRepository;
use Shared\IHashPassword;

class AuthService implements IAuthService {
    private IUserRepository $userRepository;
    private IHashPassword $passwordHacher;
    private ?User $currentUser = null;

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

    public function login(string $email, string $password): bool {
        $user = $this->userRepository->getItemByEmail($email);
        if ($user === null || !$this->validatePassword($password, $user->getPasswordHash())) {
            return false;
        }

        $this->currentUser = $user;
        // Add session handling logic here
        return true;
    }

    public function register(string $email, string $password, array $data): bool {
        if ($this->userRepository->getItemByEmail($email)) {
            throw new \Exception('User already exists');
        }

        $hashedPassword = $this->passwordHacher->hashPassword($password);
        $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();
        }
        // Create a new user instance (you should expand on this with more data as needed)
            $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;
        // Add session handling logic here
        return true;
    }

    public function logout(): void {
        $this->currentUser = null;
        // Add session handling logic here
    }

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

    private function validatePassword(string $password, string $hash): bool {
        // Implement password validation logic (e.g., using password_verify if using bcrypt)
    }
}
