<?php

namespace App\Models;

use App\Entities\UserSNSEntity;

class UserSNSModel extends BaseModel
{
    protected $table = "tw_user_sns";
    protected $returnType = UserSNSEntity::class;
    public function __construct()
    {
        parent::__construct('UserSNS');
        $this->allowedFields = [
            ...$this->allowedFields,
            "site", "id", 'name', "email", "detail", "status"
        ];
        $this->validationRules = [...$this->validationRules, ...$this->getFieldRules($this->allowedFields),];
    }
    public function getTitleField(): string
    {
        return 'name';
    }

    public function getFieldRule(string $field, array $rules, string $action = ""): array
    {
        switch ($field) {
            case "id":
                $rules[$field] =   "required|trim|string";
                $rules[$field] .= $action == "insert" ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case $this->getTitleField():
                $rules[$field] =   "required|trim|string";
                break;
            case "email":
                $rules[$field] =   "required|valid_email";
                break;
            case "detail":
                $rules[$field] =   "if_exist|string";
                break;
            case "status":
                $rules[$field] =   "required|string";
                break;
            default:
                $rules = parent::getFieldRule($field, $rules, $action);
                break;
        }
        return $rules;
    }
    public function getEntity($conditions): UserSNSEntity
    {
        return $this->where($conditions)->first() ?: throw new \Exception(__FUNCTION__ . "에서 {$this->getClassName()}의 해당 데이터가 없습니다.");
    }
    public function create(array $formDatas): UserSNSEntity
    {
        return $this->create_process(new UserSNSEntity(), $formDatas);
    }
    public function modify(UserSNSEntity $entity, array $formDatas): UserSNSEntity
    {
        return $this->modify_process($entity, $formDatas);
    }

    //Index관련
    public function setIndexWordFilter(string $word): void
    {
        if ($word !== DEFAULTS['EMPTY']) {
            parent::setIndexWordFilter($word);
            $this->orLike("email", $word, "both");
        }
    }
}
