<?php

namespace App\Libraries\MySocket\GoogleSocket;

use App\Entities\UserSNSEntity;
use CodeIgniter\Exceptions\ConfigException;
use Google\Client;
use Google\Service\Oauth2;

class API extends GoogleSocket
{
	public function __construct()
	{
		parent::__construct();
	}

	public function getClient(): Client
	{
		if ($this->_client === null) {
			$this->_client = new Client();
			$this->_client->setClientId(env('socket.google.client.id'));
			$this->_client->setClientSecret(env('socket.google.client.key'));
			$this->_client->setRedirectUri(base_url(env('socket.google.client.callback_url')));
			$this->_client->addScope(Oauth2::USERINFO_EMAIL);
			$this->_client->addScope(Oauth2::USERINFO_PROFILE);
			// $this->setPrompt('select_account consent');
			// $this->setAccessType('offline');
			// SSL 검증 비활성화
			$this->_client->setHttpClient(new \GuzzleHttp\Client(['verify' => false]));
			// 사용자 정의 CA 번들 사용
			// $this->setHttpClient(new \GuzzleHttp\Client(['verify' => '/path/to/cacert.pem']));
		}
		return $this->_client;
	}

	public function createAuthUrl(): string
	{
		return $this->getClient()->createAuthUrl();
	}

	//TokenInfo
	// (object) array(
	//    'access_token' => 'sdfsdfsdfsdf',
	//    'expires_in' => 3599,
	//    'refresh_token' => 'sdfsdf',
	//    'scope' => 'https://www.googleapis.com/auth/userinfo.profile openid https://www.googleapis.com/auth/userinfo.email',
	//    'token_type' => 'Bearer',
	//    'id_token' => 'fadfasdfsadf.sdfsdf.sdfsd',
	// )	
	// id_token(.을기준으로 base64_decode):
	// DEBUG - 2024-10-10 07:25:01 --> array (
	// 	'alg' => 'RS256',
	// 	'kid' => 'a50f6e70ef4bsdfsdffb8f54dce9ee',
	// 	'typ' => 'JWT',
	//   )
	//   DEBUG - 2024-10-10 07:25:01 --> array (
	// 	'iss' => 'accounts.google.com',
	// 	'azp' => '105607sdfsdfsdfsdfogleusercontent.com',
	// 	'aud' => '1056073563687sdfsdfsdftent.com',
	// 	'sub' => '103667492342341096838',
	// 	'email' => 'sdfsdfsdf@gmail.com',
	// 	'email_verified' => true,
	// 	'at_hash' => 'RKDNDFSrkeZ_LWg',
	// 	'iat' => 1728df545102,
	// 	'exp' => 172854df8702,
	//   )
	//   DEBUG - 2024-10-10 07:25:01 --> NULL
	public function setToken(string $access_code): void
	{
		// 토큰 정보 가져오기
		$tokenInfo = $this->getClient()->fetchAccessTokenWithAuthCode($access_code);
		if (isset($tokenInfo['error'])) {
			throw new ConfigException($tokenInfo['error']);
		}
		// log_message("debug", var_export($tokenInfo, true));
		$this->_access_token = $tokenInfo[$this->_token_name];
		// Google Service에 접근하기 위해 Access Token 설정
		$this->getClient()->setAccessToken([
			'access_token' => $this->_access_token,
			'expires_in' => 3600,
			'created' => time(),
		]);
		if ($this->getClient()->isAccessTokenExpired()) {
			$this->getClient()->refreshToken($tokenInfo['refresh_token']);
		}
		// 세션에 Token 값 설정
		$this->session->set($this->_token_name, $this->_access_token);
	}

	public function getUserSNSEntity(): UserSNSEntity
	{
		$this->getClient()->setAccessToken($this->getToken());
		$oauth = new Oauth2($this->getClient());
		$userInfo = $oauth->userinfo->get();
		$detail = var_export($userInfo, true);
		// log_message("debug", $detail);
		// 사용자정보 설정하기
		return $this->setUserSNSEntity($userInfo->id, $userInfo->name, $userInfo->email, $detail);
	}
}
