<?php

namespace App\Models\Cloudflare;

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

class AccountModel extends CommonModel
{
    const TABLE = "cloudflareaccount";
    const PK    = "uid";
    const TITLE = "title";
    protected $table = self::TABLE;
    protected $primaryKey = self::PK;
    protected $useAutoIncrement = false;
    protected $returnType = AccountEntity::class; //object,array,entity명::class
    protected $allowedFields = [self::PK, self::TITLE, 'authkey', 'oldkey', 'title', 'type', 'status', 'updated_at', 'created_at'];
    protected $useTimestamps = true;
    public function __construct()
    {
        parent::__construct();
    }
    public function getTitleField(): string
    {
        return self::TITLE;
    }
    public function getFieldRule(string $field, array $rules): array
    {
        switch ($field) {
            case self::TITLE:
                $rules[$field] = "required|valid_emailvalid_email|is_unique[cloudflareauth.id]";
                break;
            case 'id':
                $rules[$field] = "required|valid_emailvalid_email|is_unique[cloudflareauth.id]";
                break;
            case "authkey":
                $rules[$field] = "required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]";
                ;
                break;
            case "oldkey":
                $rules[$field] = "if_exist|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]";
                break;
            case "type":
                $rules[$field] = "if_exist|in_list[standard,enterprise]";
                break;
            default:
                $rules = parent::getFieldRule($field, $rules);
                break;
        }
        return $rules;
    }
    public function getFormFieldOption(string $field, array $options = []): array
    {
        switch ($field) {
            default:
                $this->orderBy(self::TITLE, 'asc');
                $options = parent::getFormFieldOption($field, $options);
                break;
        }
        return $options;
    }
    public function getEntityByPK(int $uid): null|AccountEntity
    {
        $this->where($this->getPKField(), $uid);
        return $this->getEntity();
    }
    public function getEntityByID(string $id): null|AccountEntity
    {
        $this->where('id', $id);
        return $this->getEntity();
    }
    //create용
    public function create(array $formDatas = []): AccountEntity
    {
        return $this->create_process(new AccountEntity(), $formDatas);
    }
    //modify용
    public function modify(AccountEntity $entity, array $formDatas): AccountEntity
    {
        return $this->modify_process($entity, $formDatas);
    }
}
