<?php

namespace App\Libraries\Cloudflare;

use App\Models\Cloudflare\AuthModel;
use App\Models\Cloudflare\AccountModel;
use App\Libraries\MySocket\CloudflareSocket;
use App\Libraries\CommonLibrary;
use App\Entities\Cloudflare\AuthEntity;

abstract class Cloudflare extends CommonLibrary
{
	private $_auth_entity = null;
	private $_authModel = null;
	private $_accountModel = null;
	protected function __construct(AuthEntity $auth_entity)
	{
		$this->_auth_entity = $auth_entity;
		parent::__construct();
	}
	abstract protected function getArrayByResult($result, array $formDatas = []): array;
	final public function getMySocket(): CloudflareSocket
	{
		if ($this->_mySocket === null) {
			$this->_mySocket = new CloudflareSocket($this->getAuthEntity());
		}
		return $this->_mySocket;
	}
	final protected function getAuthEntity(): AuthEntity
	{
		if ($this->_auth_entity === null) {
			throw new \Exception(__FUNCTION__ . "에서 인증정보가 없습니다.");
		}
		return $this->_auth_entity;
	}
	final protected function getAuthModel(): AuthModel
	{
		if ($this->_authModel === null) {
			$this->_authModel = new AuthModel();
		}
		return $this->_authModel;
	}
	final protected function getAccountModel(): AccountModel
	{
		if ($this->_accountModel === null) {
			$this->_accountModel = new AccountModel();
		}
		return $this->_accountModel;
	}

	private function reload_page(string $uri, int $page, int $per_page = 20): mixed
	{
		$query = [
			'name' => '',
			'status' => '',
			'order' => 'name',
			'direction' => 'asc',
			'page' => $page,
			'per_page' => $per_page,
			'match' => 'all',
			'cache_buster' => time(), // 캐시 무효화를 위한 파라미터 추가
		];
		// log_message("debug", var_export($query, true));
		$response = $this->getMySocket()->get($uri, $query);
		$cf = json_decode($response->getBody());
		if (!$cf->success) {
			$message = __FUNCTION__ . "에서 실패:\nresponse:" . var_export($cf, true);
			log_message("error", $message);
			throw new \Exception($message);
		}
		// log_message("debug", "Page {$page} response: " . var_export($cf->result_info, true));
		return $cf;
	}
	final protected function reload_procedure(string $uri): array
	{
		$page = 1; //1부터 시작
		//한번에 가져올수 있는 갯수 (countfalre 5~50사이)
		$cf = $this->reload_page($uri, $page);
		$per_page = $cf->result_info->per_page;
		$total_page = $cf->result_info->total_pages;
		$results = $cf->result;
		for ($i = $page + 1; $i < $total_page; $i++) {
			$cf = $this->reload_page($uri, $i, $per_page);
			$results = array_merge($results, $cf->result);
			log_message("debug", "현재: page[{$i}/{$total_page}] , result수[" . count($results) . "]");
		}
		return $results;
	}
}
