<?php

namespace App\Models\Cloudflare\API;

use App\Entities\Cloudflare\API\AccountEntity;
use CodeIgniter\Model;

class AccountModel extends Model
{
    const PARENT_FIELD = "auth_uid";
    protected $DBGroup          = 'default';
    protected $table            = 'cloudflareaccount';
    protected $primaryKey       = 'uid';
    protected $useAutoIncrement = false;
    protected $insertID         = 0;
    protected $returnType       = 'array'; //object,array,entity명::class
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = ['uid', 'auth_uid', 'title', 'type', 'status', 'updated_at', 'created_at'];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [
        'uid'               => 'if_exist|min_length[10]|max_length[200]',
        'auth_uid'          => 'if_exist|numeric',
        'title'             => 'if_exist|min_length[10]|max_length[200]',
        'type'              => 'if_exist|in_list[standard]',
        'status'            => 'if_exist|in_list[use,unuse]',
        'updated_at'        => 'if_exist|valid_date',
        'created_at'        => 'if_exist|valid_date',
    ];
    protected $validationMessages   = [];
    protected $skipValidation       = true;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    public function getEntity(string $uid): null|AccountEntity
    {
        $entity = $this->asObject(AccountEntity::class)->where('uid', $uid)->first();
        if (is_null($entity)) {
            throw new \Exception(__METHOD__ . "에서 {$uid} 해당 정보가 없습니다.");
        }
        return $entity;
    }

    //Account Status
    public function setStatusByAuth(int $auth_uid, $status)
    {
        $this->set('status', $status)
            ->where('auth_uid', $auth_uid)
            ->update();
    }
    //Index 검색용
    public function setIndexWordFilter(string $word)
    {
        $this->like('title', $word, 'both'); //befor , after , both
    }
    public function setIndexDateFilter($start, $end)
    {
        $this->where('created_at >=', $start);
        $this->where('created_at <=', $end);
    }

    //존재하는지 체크
    public function isUniqueApikey(string $uid): bool
    {
        $this->where('uid', $uid);
        return is_null($this->find()) ? true : false;
    }
}
