<?php

namespace App\Models\Cloudflare;

use App\Entities\Cloudflare\AuthEntity;
use App\Models\CommonModel;

class AuthModel extends CommonModel
{
    const TABLE = "cloudflareauth";
    const PK    = "uid";
    const TITLE = "id";
    protected $table = self::TABLE;
    protected $primaryKey = self::PK;
    protected $useAutoIncrement = true;
    protected $returnType = AuthEntity::class; //object,array,entity명::class
    protected $allowedFields = [self::TITLE, 'authkey', 'oldkey', 'status', 'updated_at', 'created_at'];
    protected $useTimestamps = true;
    public function __construct()
    {
        parent::__construct();
    }
    public function getTitleField(): string
    {
        return self::TITLE;
    }
    public function getFieldRule(string $action, string $field): string
    {
        switch ($field) {
            case self::TITLE:
                $rule = "required|trim|valid_email";
                $rule .= $action == "create" ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case "authkey":
                $rule = "required|trim|string";
                $rule .= $action == "create" ? "|is_unique[{$this->table}.{$field}]" : "";
                break;
            case "oldkey":
                $rule = "if_exist|trim|string";
                break;
            default:
                $rule = parent::getFieldRule($action, $field);
                break;
        }
        return $rule;
    }
    public function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            default:
                $this->orderBy(self::PK, 'asc');
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    public function getEntityByPK(string $uid): null|AuthEntity
    {
        $this->where($this->getPKField(), intval($uid));
        return $this->getEntity();
    }
    public function getEntityByID(string $id): null|AuthEntity
    {
        $this->where(self::TITLE, $id);
        return $this->getEntity();
    }
    //create용
    public function create(array $formDatas = []): AuthEntity
    {
        return $this->create_process(new AuthEntity(), $formDatas);
    }
    //modify용
    public function modify(AuthEntity $entity, array $formDatas): AuthEntity
    {
        return $this->modify_process($entity, $formDatas);
    }
}
