<?php

namespace App\Libraries\MySocket;

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

abstract class CloudflareSocket extends CommonLibrary
{
	private $_authModel = null;
	private $_accountModel = null;
	private $_client = null;
	private $_auth_entity = null;
	protected function __construct(AuthEntity $auth_entity)
	{
		parent::__construct();
		$this->_auth_entity = $auth_entity;
	}
	abstract protected function getArrayByResult($result, array $formDatas = []): array;
	final protected function getClient(): CloudflareClient
	{
		if ($this->_client === null) {
			// Guzzle HTTP 클라이언트를 설정하면서 Cloudflare API 토큰 사용
			$this->_client = new CloudflareClient([
				'base_uri' => 'https://api.cloudflare.com/client/v4/',
				'headers' => [
					'X-Auth-Email' => $this->_auth_entity->getID(), // 인증 토큰 사용
					'X-Auth-Key' => $this->_auth_entity->getAuthKey(), // 인증 토큰 사용
					'Content-Type' => 'application/json',
				],
				'verify' => false  // SSL 인증서 검증을 비활성화
			]);
		}
		return $this->_client;
	}
	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;
	}
	final protected function reload_procedure($uri): array
	{
		$page = 1; //1부터 시작
		$results = [];
		do {
			$query = [
				'page' => $page,
				'per_page' => CloudflareClient::REQUEST_PERPAGE_MAX,
				'match' => 'all',
			];
			$response = $this->getClient()->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);
			}
			$results = array_merge($results, $cf->result);
			if (count($cf->result) < CloudflareClient::REQUEST_PERPAGE_MAX) {
				break;
			}
			$page++;
		} while (true);
		return $results;
	}
}
