<?php

namespace App\Libraries\MyAuth;

use App\Entities\UserEntity;
// use App\Libraries\MySocket\GoogleSocket\CURL;
use App\Libraries\MySocket\GoogleSocket\API as GoogleSocket;
use App\Models\UserModel;
use CodeIgniter\Exceptions\PageNotFoundException;

class GoogleAuth extends MyAuth
{
	private ?UserModel $_model = null;
	private string $_access_code = "";
	public function __construct()
	{
		parent::__construct();
	}

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

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

	public function checkUser(string $access_code): UserEntity
	{
		try {
			$this->_access_code = $access_code;
			// Google 서비스 설정
			$userSNS_entity = $this->getMySocket()->getUserSNSEntity();

			//local db 사용와의 연결 확인
			$userModel = model(UserModel::class);
			$user_entity = $userModel->getEntityByID($userSNS_entity->getID());
			if ($user_entity === null) {
				throw new PageNotFoundException("{$userSNS_entity->getSite()}의{$userSNS_entity->getEmail()}:{$userSNS_entity->getTitle()}님은 아직 사용자 연결이 이루어지지 않았습니다. ");
			}
			return $user_entity;
		} catch (\Google_Service_Exception $e) {
			log_message('error', '구글 서비스 예외: ' . $e->getMessage());
			throw new PageNotFoundException("구글 로그인 중 오류가 발생했습니다. 다시 시도해 주세요.");
		} catch (\Exception $e) {
			log_message('error', $e->getMessage());
			throw new PageNotFoundException("관리자에게 문의하시기 바랍니다.\n{$e->getMessage()}");
		}
	}
}
