<?php

namespace common\logic\User\User\Service;

use common\logic\AbstractBuilder;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\User\User\Model\User;
use common\logic\User\User\Repository\UserRepository;

class UserBuilder extends AbstractBuilder
{
    protected UserRepository $userRepository;

    public function loadDependencies(): void
    {
        $this->userRepository = $this->loadService(UserRepository::class);
    }

    public function instanciateUser(): User
    {
        $user = new User();

        return $user;
    }

    public function initPassword(User $user, string $password)
    {
        $this->setPassword($user, $password);
        $this->generateAuthKey($user);
    }

    public function initProducer(User $user, Producer $producer)
    {
        $user->id_producer = $producer->id;
        $user->status = User::STATUS_PRODUCER;
    }

    /**
     * Met à jour la date de dernière connexion de l'utilisateur.
     */
    public function updateUserLastConnection(User $user)
    {
        $user->date_last_connection = date('Y-m-d H:i:s');
        $user->save();
    }

    /**
     * Generates password hash from password and sets it to the model
     */
    public function setPassword(User $user, string $password): void
    {
        $user->password_hash = \Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey(User $user): void
    {
        $user->auth_key = \Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken(User $user): void
    {
        $user->password_reset_token = \Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken(User $user)
    {
        $user->password_reset_token = null;
    }

    public function deleteAccess(User $user): bool
    {
        $user->id_producer = 0;
        $user->status = User::STATUS_ACTIVE;
        return $user->save();
    }
}