<?php

namespace apexl\Io\modules\user\entities\operators;

use apexl\entityCore\helpers\Condition;
use apexl\Io\modules\user\collections\userCollection;
use apexl\Io\operators\entityDatabaseOperator;
use apexl\Vault\exceptions\ExecutionException;
use Exception;

class userOperator extends entityDatabaseOperator
{
    public function __construct($table, $primaryKey = 'id')
    {
        parent::__construct($table, $primaryKey);
    }

    /**
     * @throws ExecutionException
     */
    public function getUserByEmail($email): array
    {
        $entity = $this->vault->select($this->dbTable)->fields()->where('email', $email)->execute()->fetchAssoc();

        return ['updateEntityData' => true, 'data' => $entity];
    }

    /**
     * @throws ExecutionException
     */
    public function getUserByNfcKey($key): array
    {
        $entity = $this->vault->select($this->dbTable)->fields()->where('nfc_key', $key)->execute()->fetchAssoc();

        return ['updateEntityData' => true, 'data' => $entity];
    }

    public function getUsersByRoleId(int $roleId): userCollection
    {
        try {
            $ids = $this->vault->select('users__roles')
                ->fields('user')
                ->where('role', $roleId)
                ->execute()
                ->fetchAll();

            return userCollection::loadMultiple([
                Condition::in('id', array_column($ids, 'user')),
            ]);
        } catch (Exception $e) {
            logger()->error('Error finding users by role Id: {message}', [
                'message' => $e->getMessage(),
                'exception' => $e,
            ]);

            return new userCollection();
        }
    }


    public function markForgottenPasswordLinkUsed($hash)
    {
        $this->vault->update('password_reset')->fields(['used' => 1])->where('hash', $hash)->execute();
    }

    public function getForgottenPasswordLink($string)
    {
        return $this->vault->select("password_reset")->fields()->where('hash', $string)->execute()->fetchAssoc();
    }
}
