<?php

namespace App\Libraries\MySocket\GoogleSocket;

use Config\Services;
use CodeIgniter\Exceptions\PageNotFoundException;
use App\Models\UserSNSModel;
use App\Libraries\MySocket\MySocket;
use App\Entities\UserSNSEntity;

abstract class GoogleSocket extends MySocket
{
	private string $_site = "GOOGLE";
	private ?UserSNSModel $_model = null;
	protected $_client = null;
	protected $session;
	protected string $_access_token = "";
	protected string $_token_name = "access_token";
	public function __construct()
	{
		$this->session = Services::session();
	}
	abstract public function getClient(): mixed;
	abstract public function createAuthUrl(): string;
	abstract public function setToken(string $access_code): void;
	abstract public function getUserSNSEntity(): UserSNSEntity;
	final public function getToken(): string
	{
		return $this->session->get($this->_token_name);
	}
	final public function getSite(): string
	{
		return $this->_site;
	}
	final protected function getModel(): UserSNSModel
	{
		if ($this->_model === null) {
			$this->_model = model(UserSNSModel::class);
		}
		return $this->_model;
	}
	final protected function setUserSNSEntity(string $id, string $name, string $email, string $detail): UserSNSEntity
	{
		$this->getModel()->where(UserSNSModel::SITE, $this->getSite());
		$entity = $this->getModel()->getEntityByID($id);
		if ($entity === null) {
			//Transaction Start
			$this->getModel()->transStart();
			try {
				//없다면 새로 등록
				$formDatas = [
					'site' => $this->getSite(),
					'id' => $id,
					'name' => $name,
					'email' => $email,
					'detail' => $detail,
					'status' => 'unuse',
				];
				$entity = $this->getModel()->create($formDatas);
				$this->getModel()->transCommit();
			} catch (\Exception $e) {
				//Transaction Rollback
				$this->getModel()->transRollback();
				log_message("error", $e->getMessage());
				throw new \Exception(__FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
			}
		}
		//상태가 use(승인완료)가 아니라면
		if ($entity->status !== DEFAULTS['STATUS']) {
			throw new PageNotFoundException("{$entity->getSite()}의{$entity->getEmail()}:{$entity->getTitle()}님은 {$entity->status}입니다 ");
		}
		return $entity;
	}
}
