<?php

namespace App\Libraries\MySocket\GoogleSocket;

use App\Entities\UserSNSEntity as Entity;
use App\Libraries\MySocket\MySocket;
use App\Models\UserSNSModel as Model;
use App\Services\UserSNSService as Service;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\Session\Session;
use Config\Services;

abstract class GoogleSocket extends MySocket
{
	private string $_site = "GOOGLE";
	private ?Service $_service = null;
	protected $_client = null;
	private ?Session $_session = null;
	protected string $_access_token = "";
	protected string $_token_name = "access_token";
	public function __construct() {}
	abstract public function createAuthUrl(): string;
	abstract public function setToken(string $access_code): void;
	abstract public function signup(): Entity;
	final public function getSession(): Session
	{
		if ($this->_session == null) {
			$this->_session = Services::session();
		}
		return $this->_session;
	}
	final public function getToken(): string
	{
		return $this->getSession()->get($this->_token_name);
	}
	final public function getSite(): string
	{
		return $this->_site;
	}
	public function getService(): Service
	{
		if (!$this->_service) {
			$this->_service = new Service();
		}
		return $this->_service;
	}
	final protected function signup_process(string $id, string $name, string $email, string $detail): Entity
	{
		//이미 등록된 사용자인지 확인 후 없으면 등록 처리리
		$entity = $this->getService()->getEntity([Model::SITE => $this->getSite(), 'id' => $id], false);
		if (!$entity) {
			try {
				//없다면 새로 등록
				$formDatas = [
					'site' => $this->getSite(),
					'id' => $id,
					'name' => $name,
					'email' => $email,
					'detail' => $detail,
					'status' => 'unuse',
				];
				$entity = $this->getService()->create($formDatas);
			} catch (\Exception $e) {
				//Transaction Rollback
				log_message("error", $e->getMessage());
				throw new \Exception(__FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
			}
		}
		//상태가 use(승인완료)가 아니라면
		if ($entity->getStatus() !== $entity::DEFAULT_STATUS) {
			throw new PageNotFoundException(message: "{$entity->getSite()}의{$entity->getEmail()}:{$entity->getTitle()}님은 {$entity->status}입니다 ");
		}
		return $entity;
	}
}
