<?php

namespace App\Models;

use App\Entities\UserEntity;
use App\Models\CommonModel;

class UserModel extends CommonModel
{
    const TABLE = "user";
    const PK = "uid";
    const TITLE = "name";
    protected $table            = self::TABLE;
    protected $primaryKey       = self::PK;
    protected $returnType       = UserEntity::class;
    protected $allowedFields = [
        "id",
        "passwd",
        "name",
        "email",
        "mobild",
        "role",
        "status"
    ];
    public function __construct()
    {
        parent::__construct();
    }
    public function getTitleField(): string
    {
        return self::TITLE;
    }
    public function getFieldRule(string $action, string $field): string
    {
        if (is_array($field)) {
            throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
        }
        switch ($field) {
            case "id":
                $rule = "required|trim|min_length[4]|max_length[20]";
                $rule .= $action == "create" ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case "passwd":
                $rule = $action == "create" ? "required" : "if_exist" . "|trim|string";
                break;
            case "confirmpassword":
                $rule = $action == "create" ? "required" : "if_exist" . "|trim|string|matches[passwd]";
                break;
            case "email":
                $rule = "required|trim|valid_email";
                break;
            case "role":
                $rule  = "required|trim|string";
                break;
            default:
                $rule = parent::getFieldRule($action, $field);
                break;
        }
        return $rule;
    }
    protected function convertEntityData(string $field, array $formDatas): mixed
    {
        switch ($field) {
            case "passwd":
                $value = password_hash($formDatas[$field], PASSWORD_DEFAULT);
                break;
            case "confirmpassword":
                $value = password_hash($formDatas[$field], PASSWORD_DEFAULT);
                break;
            default:
                $value = parent::convertEntityData($field, $formDatas);
                break;
        }
        return $value;
    }

    public function getEntityByPK(string $uid): null|UserEntity
    {
        $this->where($this->getPKField(), intval($uid));
        return $this->getEntity();
    }
    public function getEntityByID(string $id): null|UserEntity
    {
        $this->where('id', $id);
        return $this->getEntity();
    }

    //create용
    public function create(array $formDatas = []): UserEntity
    {
        return $this->create_process(new UserEntity(), $formDatas);
    }
    //modify용
    public function modify(UserEntity $entity, array $formDatas): UserEntity
    {
        return $this->modify_process($entity, $formDatas);
    }
}
