<?php

namespace App\CLI;

use App\Models\Cloudflare\AuthModel;
use App\Libraries\Cloudflare\Zone;
use App\Libraries\Cloudflare\Record;
use App\Libraries\Cloudflare\Account;
use App\Entities\Cloudflare\ZoneEntity;
use App\Entities\Cloudflare\AuthEntity;
use App\Entities\Cloudflare\AccountEntity;

class Cloudflare
{
    private $_db = null;
    public function __construct()
    {
        $this->_db = \Config\Database::connect();
    }
    private function getAuthModel(): AuthModel
    {
        return new AuthModel();
    }
    private function auth_process(): array
    {
        $this->getAuthModel()->where('status', DEFAULTS["STATUS"]);
        return $this->getAuthModel()->getEntitys();
    }
    private function account_process(AuthEntity $auth_entity): array
    {
        $account = new Account($auth_entity);
        return $account->reload();
    }
    private function zone_process(AccountEntity $account_entity): array
    {
        $zone = new Zone($account_entity);
        return $zone->reload();
    }
    private function record_process(ZoneEntity $zone_entity): array
    {
        $record = new Record($zone_entity);
        return $record->reload();
    }
    public function reload(): void
    {
        //Transaction Start
        $this->_db->transStart();
        try {
            $auths = $this->auth_process();
            $accounts = [];
            foreach ($auths as $auth) {
                $accounts = $this->account_process($auth);
            }
            $zones = [];
            foreach ($accounts as $account) {
                $zones = $this->zone_process($account);
            }
            $records = [];
            foreach ($zones as $zone) {
                $records = $this->record_process($zone);
            }
            log_message("notice", "Reload 작업을 완료하였습니다.");
            $this->_db->transCommit();
        } catch (\Exception $e) {
            //Transaction Rollback
            $this->_db->transRollback();
            log_message(
                "error",
                "Reload 작업을 실패하였습니다.\n--------------\n" .
                    $e->getMessage() .
                    "\n--------------\n"
            );
        }
    }
}
