<?php

namespace App\Controllers\CLI;

use App\Controllers\BaseController;
use App\Entities\Cloudflare\AccountEntity;
use App\Entities\Cloudflare\AuthEntity;
use App\Entities\Cloudflare\ZoneEntity;
use App\Libraries\Cloudflare\Account;
use App\Libraries\Cloudflare\Record;
use App\Libraries\Cloudflare\Zone;
use App\Models\Cloudflare\AuthModel;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

class Cloudflare extends BaseController
{
    private $_db = null;
    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->_db = \Config\Database::connect();
    }
    private function auth_process(mixed $uid = false): array
    {
        $authModel = model(AuthModel::class);
        if (is_numeric($uid) && $uid > 0) {
            $authModel->where(AuthModel::PK, intval($uid));
        } else {
            $authModel->where('status', DEFAULTS["STATUS"]);
        }
        $entitys = $authModel->getEntitys();
        log_message("debug", $authModel->getLastQuery());
        return $entitys;
    }
    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(mixed $uid = false): void
    {
        //Transaction Start
        // $this->_db->transStart();
        try {
            $auths = $this->auth_process($uid);
            $accounts = [];
            foreach ($auths as $auth) {
                $accounts += $this->account_process($auth);
            }
            log_message("debug", "\n-------------총 Accounts:" . count($accounts) . "--------------------\n");
            $zones = [];
            foreach ($accounts as $key => $account) {
                $zones += $this->zone_process($account);
            }
            log_message("debug", "\n-------------총 Zones:" . count($zones) . "--------------------\n");
            foreach ($zones as $key => $zone) {
                $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"
            );
        }
    }
}
