<?php

namespace App\Services\Auth;

use App\Entities\UserEntity;
use App\Services\CommonService;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\Session\Session;

// 참고:https://github.com/SyntaxPhoenix/iloclient
abstract class AuthService extends CommonService
{
	private ?Session $_session = null;
	private $url_stack_name = "url_stack";
	protected function __construct(?IncomingRequest $request = null)
	{
		parent::__construct($request);
		$this->addClassName('Auth');
	}
	abstract public function login(array $formDatas): UserEntity;
	//Index,FieldForm관련
	final public function getSession(): Session
	{
		if (!$this->_session) {
			$this->_session = \Config\Services::session();
		}
		return $this->_session;
	}
	private function getAuthInfo(string $key = ""): array|string
	{
		$authInfo = $this->getSession()->get(SESSION_NAMES['AUTH']);
		if ($key) {
			return $authInfo[$key] ?? "";
		}
		return $authInfo;
	}
	public function getFormFields(): array
	{
		return ['id', 'passwd'];
	}
	final public function getUIDByAuthInfo(): string
	{
		return $this->getAuthInfo('uid');
	}
	final public function getIDByAuthInfo(): string
	{
		return $this->getAuthInfo('id');
	}
	final public function getNameByAuthInfo(): string
	{
		return $this->getAuthInfo('name');
	}
	final public function getRoleByAuthInfo(): string
	{
		return $this->getAuthInfo('role');
	}
	final public function isLoggedIn(): bool
	{
		return $this->getSession()->has(SESSION_NAMES['ISLOGIN']);
	}
	final public function isAccessRole(array $roles): bool
	{
		$role = $this->getRoleByAuthInfo();
		if ($role === "") {
			return false;
		}
		// 교집합이 없으면 false
		return !empty(array_intersect(explode(DEFAULTS['DELIMITER_ROLE'], $role), $roles));
	}
	final public function pushCurrentUrl(string $url): void
	{
		$this->getSession()->set($this->url_stack_name, $url);
	}
	final public function popPreviousUrl(): string
	{
		$url = $this->getSession()->get($this->url_stack_name) ?? "";
		if (!empty($url)) {
			$this->pushCurrentUrl("");
			return $url;
		}
		return '/';  // 기본 URL
	}
	final protected function login_process(UserEntity $entity): UserEntity
	{
		$this->getSession()->set(SESSION_NAMES['ISLOGIN'], true);
		$this->getSession()->set(SESSION_NAMES['AUTH'], ['uid' => $entity->getPK(), 'id' => $entity->getID(), 'name' => $entity->getTitle(), 'role' => $entity->role]);
		return $entity;
	}
	final public function logout(): void
	{
		// 세션 데이터 삭제
		$this->getSession()->remove(SESSION_NAMES['ISLOGIN']);
		$this->getSession()->remove(SESSION_NAMES['AUTH']);
		// 모든 세션 데이터 삭제
		$this->getSession()->destroy();
		// 세션 쿠키 삭제
		if (ini_get("session.use_cookies")) {
			$params = session_get_cookie_params();
			setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
		}
		// 세션 재생성
		session_start();
		$this->getSession()->regenerate(true);
	}
}
