<?php

namespace App\Services\Auth;

use App\DTOs\Auth\LocalDTO;
use App\Entities\UserEntity;
use App\Forms\Auth\LocalForm;
use App\Models\UserModel;
use CodeIgniter\Validation\Exceptions\ValidationException;
use RuntimeException;

class LocalService extends AuthService
{
	private $_form = null;
	public function __construct(UserModel $model)
	{
		parent::__construct($model);
		$this->addClassPaths('Local');
	}
	public function createDTO(array $formDatas): LocalDTO
	{
		return new LocalDTO($formDatas);
	}
	protected function getDTOClass(): string
	{
		return LocalDTO::class;
	}
	public function getFormService(): LocalForm
	{
		if ($this->_form === null) {
			$this->_form = new LocalForm();
			$this->_form->setAttributes([
				'pk_field'         => $this->model->getPKField(),
				'title_field'      => $this->model->getTitleField(),
				'table'            => $this->model->getTable(),
				'useAutoIncrement' => $this->model->useAutoIncrement(),
				'class_path'       => $this->getClassPaths(false),
			]);
		}
		return $this->_form;
	}
	public function action_init_process(string $action, array $formDatas = []): void
	{
		$fields = ['id', 'passwd'];
		$filters = [];
		switch ($action) {
			case 'login':
			case 'login_form':
				break;
		}
		$this->getFormService()->setFormFields($fields);
		$this->getFormService()->setFormRules($action, $fields);
		$this->getFormService()->setFormFilters($filters);
		$this->getFormService()->setFormOptions($action, $filters);
		$this->getFormService()->setBatchjobFilters($filters);
	}
	protected function getEntity_process(mixed $entity): UserEntity
	{
		return $entity;
	}
	protected function login_process(array $formDatas): UserEntity
	{
		//입력값 검증
		if (!$this->getFormService()->validate($formDatas)) {
			throw new ValidationException(implode("\n", service('validation')->getErrors()));
		}
		//로그인 정보확인
		$entity = $this->getEntity(['id' => $formDatas['id'], 'status' => 'AVAILABLE']);
		if (!$entity instanceof UserEntity) {
			throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 {$formDatas['id']}에 대한 로그인 정보를 찾을수 없습니다.");
		}
		if (!password_verify($formDatas['passwd'], $entity->getPassword())) {
			throw new RuntimeException(static::class . '->' . __FUNCTION__ . "에서 암호가 맞지 않습니다.");
		}
		return $entity;
	}
}
