<?php

namespace App\Libraries\MyAuth;

use App\Entities\UserEntity;
use App\Libraries\MySocket\GoogleSocket;
use App\Models\SNSUserModel;
use App\Models\UserModel;
use CodeIgniter\Exceptions\PageNotFoundException;
use Google\Service\Oauth2;

class GoogleAuth extends MyAuth
{
	private ?GoogleSocket $_mySocket = null;
	private string $_site = "GOOGLE";
	private ?SNSUserModel $_model = null;
	private string $token_code = "";
	private string $access_code = "";
	public function __construct(string $token_code, string $access_code)
	{
		parent::__construct();
		$this->token_code = $token_code;
		$this->access_code = $access_code;
	}

	public function getMySocket(): GoogleSocket
	{
		if ($this->_mySocket === null) {
			$this->_mySocket = new GoogleSocket($this->token_code);
			$this->_mySocket->setToken($this->access_code);
		}
		return $this->_mySocket;
	}

	final protected function getModel(): SNSUserModel
	{
		if ($this->_model === null) {
			$this->_model = model(SNSUserModel::class);
		}
		return $this->_model;
	}

	// throw new \Exception(__METHOD__ . "에서 데이터 처리 필요");
	// DEBUG - 2023-07-13 12:54:51 --> \Google\Service\Oauth2\Userinfo::__set_state(array(
	// 	'internal_gapi_mappings' =>
	// 	 'familyName' => 'family_name',
	// 	 'givenName' => 'given_name',
	// 	 'verifiedEmail' => 'verified_email',
	//    ),
	// 	'modelData' =>
	//    array (
	// 	 'verified_email' => true,
	// 	 'given_name' => '이름',
	// 	 'family_name' => '성',
	//    ),
	// 	'processed' =>
	//    array (
	//    ),
	// 	'email' => 'twsdfsew342s@gmail.com',
	// 	'familyName' => '성',
	// 	'gender' => NULL,
	// 	'givenName' => '이름',
	// 	'hd' => NULL,
	// 	'id' => '103667492432234234236838324',
	// 	'link' => NULL,
	// 	'locale' => 'ko',
	// 	'name' => '성이름',
	// 	'picture' => 'https://lh3.googleusercontent.com/a/AAcHTteFSgefsdfsdRJBkJA2tBEmg4PQrvI1Ta_5IXu5=s96-c',
	// 	'verifiedEmail' => true,
	//  ))
	public function checkUser(): UserEntity
	{
		try {
			//Google 서비스 설정
			$service = new Oauth2($this->getMySocket());
			$authInfo = $service->userinfo->get();
			log_message('debug', var_export($authInfo, true));
			//기존 등록된 사용자가 있는지 검사
			$this->getModel()->where(SNSUserModel::SITE, $this->_site);
			$entity = $this->getModel()->getEntityByID($authInfo['id']);
			if ($entity === null) {
				//없다면 새로 등록
				$formDatas = [
					'site' => $this->_site,
					'id' => $authInfo['id'],
					'name' => $authInfo['name'],
					'email' => $authInfo['email'],
					'detail' => json_encode($authInfo),
					'status' => 'standby',
				];
				$entity = $this->getModel()->create($formDatas);
			}
			//상태가 use(승인완료)가 아니라면
			if (
				$entity->status !== DEFAULTS['STATUS']
			) {
				throw new PageNotFoundException("{$this->_site}}의{$authInfo['email']}:{$authInfo['name']}님은 " . $entity->status . "입니다");
			}
			//local db 사용와의 연결 확인
			$userModel = model(UserModel::class);
			$user_entity = $userModel->getEntityByID($entity->getID());
			if ($user_entity === null) {
				throw new PageNotFoundException("{$this->_site}의{$authInfo['email']}:{$authInfo['name']}님은 아직 사용자 연결이 이루어지지 않았습니다. ");
			}
			return $user_entity;
		} catch (\Exception $e) {
			log_message('error', $e->getMessage());
			throw new PageNotFoundException("관리자에게 문의하시기 바랍니다.<BR>{$e->getMessage()}");
		}
	}
}
