<?php

namespace App\Models;

use App\Entities\UserEntity;

class UserModel extends CommonModel
{
    protected $table            = 'tw_user';
    // protected $primaryKey       = 'uid';
    protected $useAutoIncrement = false;
    protected $allowedFields    = ['uid', 'id', 'email', 'passwd', 'name',  'role', 'status', 'updated_at'];
    protected $validationRules      = [
        'uid'               => 'required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]',
        'id'                => 'required|min_length[4]|max_length[20]',
        'passwd'            => 'required|trim|min_length[4]|max_length[150]',
        'name'              => 'required|min_length[2]|max_length[20]',
        'email'             => 'required|valid_email',
        'role'              => 'required|string',
        'status'            => 'if_exist|string',
        'updated_at'        => 'if_exist|valid_date',
        'created_at'        => 'if_exist|valid_date',
    ];

    public function getEntityByField($field, $value): ?UserEntity
    {
        return $this->asObject(UserEntity::class)->where($field, $value)->first();
    }
    public function getEntity(string $uid): ?UserEntity
    {
        return $this->getEntityByField($this->primaryKey, $uid);
    }
    public function create(array $datas): UserEntity
    {
        $entity = new UserEntity();
        $entity->uid = $this->getUUIDv5_CommonTrait(UUIDS['NAMESPACE'], UUIDS['SECRET']);
        foreach ($datas as $field => $value) {
            $entity->$field = $field === 'passwd' ? $entity->getEncryptedPassword($value) : $value;
        }
        return parent::create_process($entity);
    }
    public function modify(UserEntity $entity, array $datas): UserEntity
    {
        foreach ($datas as $field => $value) {
            if ($entity->$field != $datas[$field]) {
                $entity->$field = $field === 'passwd' ? $entity->getEncryptedPassword($value) : $value;
            }
        }
        return parent::modify_process($entity);
    }

    //Index관련
    public function setIndexWordFilter(string $word)
    {
        parent::setIndexWordFilter($word);
        $this->orLike('id', $word, 'both');
        $this->orLike('name', $word, 'both'); //befor , after , both
    }
    public function setIndexOrderBy($field, $order = 'ASC')
    {
        $this->orderBy("name", "ASC");
        parent::setIndexOrderBy($field, $order);
    }
}
