<?php

namespace App\Libraries\Cloudflare;

use App\Entities\Cloudflare\RecordEntity;
use App\Entities\Cloudflare\ZoneEntity;
use App\Models\Cloudflare\RecordModel;

class Record extends Cloudflare
{
    private $_model = null;
    private $_zone_entity = null;
    public function __construct(ZoneEntity $zone_entity)
    {
        $this->_zone_entity    = $zone_entity;
        $account_entity = $this->getAccountModel()->getEntityByPK($this->_zone_entity->getParent());
        if ($account_entity === null) {
            throw new \Exception("해당 계정정보를 찾을수 없습니다.");
        }
        $auth_entity = $this->getAuthModel()->getEntityByPK($account_entity->getParent());
        if ($auth_entity === null) {
            throw new \Exception("해당 계정정보를 찾을수 없습니다.");
        }
        parent::__construct($auth_entity);
    }
    protected function getModel(): RecordModel
    {
        if ($this->_model === null) {
            $this->_model = new RecordModel();
        }
        return $this->_model;
    }
    public function getArrayByResult($result, array $formDatas = []): array
    {
        $formDatas[RecordModel::PK]     = $result->id;
        $formDatas[RecordModel::PARENT] = $result->zone_id;
        $formDatas[RecordModel::TITLE]  = $result->name;
        $formDatas['type']              = $result->type;
        $formDatas['content']           = $result->content;
        $formDatas['ttl']               = (int)$result->ttl;
        $formDatas['proxiable']         = $result->proxiable ? "on" : "off";
        $formDatas['proxied']           = $result->proxied ? "on" : "off";
        $formDatas['locked']            = "on";
        if (isset($result->locked) && $result->locked) {
            $formDatas['locked'] = "off";
        }
        $formDatas['updated_at'] = date("Y-m-d H:i:s");
        $formDatas['created_at'] = $result->created_on;
        return $formDatas;
    }
    public function create(string $host, string $type, string $content, string $proxied): RecordEntity
    {
        //Socket용
        //호스트생성을 위해 Cloudflare에 전송
        $datas = [
            'name'    => $host,
            'type'    => $type,
            'content' => $content,
            'proxied' => $proxied === 'on' ? true : false
        ];
        $cf = $this->getMySocket()->post("zones/{$this->_zone_entity->getPK()}/dns_records", $datas);
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            $message = "Record:" . __FUNCTION__ . "에서 실패:\nrequest:" . var_export($datas, true) . "\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        //DB생성
        $formDatas = $this->getArrayByResult($cf->result);
        return $this->getModel()->create($formDatas);
    }
    public function modify(RecordEntity $entity, array $formDatas): RecordEntity
    {
        //TTL값은 CDN(proxied)가 사용함일때는 무조건 1, 않함일때는 120이 적용
        $datas = [
            'type'    => isset($formDatas['type']) ? $formDatas['type'] : $entity->type,
            'name'    => isset($formDatas['host']) ? $formDatas['host'] : $entity->host,
            'content' => isset($formDatas['content']) ? $formDatas['content'] : $entity->content,
            'proxied' => $entity->proxied == 'on' ? true : false,
            'ttl'     => intval($entity->ttl),
        ];
        if (isset($formDatas['proxied'])) {
            if ($formDatas['proxied'] === 'on') {
                $datas['proxied'] = true;
                $datas['ttl']     = 1;
            } else {
                $datas['proxied'] = false;
                $datas['ttl']     = 120;
            }
        }
        // 인코딩된 JSON을 확인
        // throw new \Exception("Record:" . __FUNCTION__ . "\n" . json_encode($datas, JSON_PRETTY_PRINT) . "\n" . var_export($datas, true));
        $cf = $this->getMySocket()->put("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}", $datas);
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            $message = "Record:" . __FUNCTION__ . "에서 실패:\nrequest:" . var_export($datas, true) . "\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        //DB수정
        $formDatas = $this->getArrayByResult($cf->result);
        return $this->getModel()->modify($entity, $formDatas);
    }
    public function delete(RecordEntity $entity): RecordEntity
    {
        $cf = $this->getMySocket()->delete("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}");
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            $message = "Record:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        //DB삭제
        $this->getModel()->where(RecordModel::PK, $entity->getPK());
        $this->getModel()->delete();
        return $entity;
    }
    public function sync(RecordEntity $entity): RecordEntity
    {
        // 기존 Sync형태
        $cf = $this->getMySocket()->get("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}");
        $cf = json_decode($cf->getBody());
        if (!$cf->success) {
            $message = "Record:" . __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
            log_message("error", $message);
            throw new \Exception($message);
        }
        //  DB수정
        log_message("debug", var_export($cf->result, true));
        $entity = $this->getModel()->modify($entity, $this->getArrayByResult($cf->result));
        //Async형태
        // $promise = $this->getMySocket()getAsync("zones/{$this->_zone_entity->getPK()}/dns_records/{$entity->getPK()}");
        // $entity =$promise->then(
        //     onFulfilled: function ($response)  use ($entity): RecordEntity {
        //         $record = json_decode($response->getBody(), true)['result'];
        //         log_message("debug", var_export($record));
        //         //DB수정
        //         return $this->getModel()->modify($entity, $this->getArrayByResult($record));
        //     },
        //     onRejected: function ($error) {
        //         log_message('error', 'Failed to fetch DNS records: ' . $error->getMessage());
        //         throw new \Exception('Failed to fetch DNS records: ' . $error->getMessage());
        //     }
        // );
        // $promise->wait();
        return $entity;
    }
    //Reload
    public function reload(): array
    {
        log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리 시작-----");
        $entitys = [];
        foreach ($this->reload_procedure("zones/{$this->_zone_entity->getPK()}/dns_records") as $result) {
            $formDatas     = $this->getArrayByResult($result);
            $entity        = $this->getModel()->modify($this->getModel()->getEntity(), $formDatas);
            $entitys[$entity->getPK()] = $entity;
        }
        //부모키를 기준으로 CF에 존재하지 않는 데이터 DB삭제
        $this->getModel()->where(RecordModel::PARENT, $this->_zone_entity);
        $this->getModel()->whereNotIn(RecordModel::PK, array_keys($entitys));
        $this->getModel()->delete();
        log_message("notice", "-----{$this->_zone_entity->getTitle()} 처리[" . count($entitys) . "개] 완료-----");
        return $entitys;
    }
}
