<?php

namespace App\Models\Cloudflare\API;

use App\Entities\Cloudflare\API\RecordEntity;
use App\Libraries\Log\Log;
use CodeIgniter\Model;

class RecordModel extends Model
{
    const PARENT_FIELD = "zone_uid";
    protected $DBGroup          = 'default';
    protected $table            = 'cloudflarerecord';
    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', 'zone_uid', 'type', 'host', 'content', 'ttl', 'proxiable', 'proxied', 'fixed', 'locked', 'updated_at', 'crated_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]',
        'zone_uid'          => 'if_exist|min_length[10]|max_length[200]',
        'host'              => 'if_exist|string',
        'content'           => 'if_exist|string',
        'type'              => 'if_exist|string',
        'ttl'               => 'if_exist|numeric',
        'proxiable'         => 'if_exist|in_list[on,off]',
        'proxied'           => 'if_exist|in_list[on,off]',
        'fixed'             => 'if_exist|in_list[on,off]',
        'locked'            => 'if_exist|in_list[on,off]',
        '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 getTableName()
    {
        return $this->table;
    }

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

    //Index 검색어용
    public function setIndexWordFilter(string $word)
    {
        $this->like('host', $word, 'before'); //befor , after , both
        $this->orWhere('content', $word); //befor , after , both
    }
    public function setIndexDateFilter($start, $end)
    {
        $this->where('created_at >=', $start);
        $this->where('created_at <=', $end);
    }
    public function setIndexOrderBy($field, $order = 'ASC')
    {
        $this->orderBy("zone_uid ASC, host ASC, {$field} {$order}");
    }

    //도메인이 이미 존재하는지 체크
    public function isUniqueHost($zone_uid, string $host, string $content): bool
    {
        $this->where('zone_uid', $zone_uid);
        $this->where('host', $host);
        $this->where('content', $content);
        return is_null($this->first()) ? true : false;
    }

    //CDN값 수정 못하는 고정 Record 처리
    public function setFixedCDNRecord(array $hosts)
    {
        if (count($hosts)) {
            $this->whereIn('host', $hosts)->set(['fixed' => 'on'])->update();
            Log::add("notice", "-----set fixed Records " . implode(",", $hosts) . "처리 완료-----");
        }
    }
}
