<?php

namespace App\Controllers\Auth;

use App\Controllers\CommonController;

use App\Entities\UserEntity;
use App\Helpers\AuthHelper;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;

abstract class AuthController extends CommonController
{

    public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);
        $this->layout = "auth";
        $this->uri_path = "auth/";
        $this->view_path = "auth" . DIRECTORY_SEPARATOR;
        $this->content_title     = "사용자인증";
    }
    abstract protected function getSNSButton(): string;
    abstract protected function login_process(array $formDatas): UserEntity;
    protected function getResultFail(string $message = MESSAGES["FAILED"]): RedirectResponse
    {
        if ($this->request->getMethod() === 'POST') {
            return redirect()->back()->withInput()->with('error', $message);
        }
        return redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
    }
    protected function getResultSuccess(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        switch ($this->getService()->getAction()) {
            case 'create': //Login처리
                $result = redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
                break;
            default:
                $result = parent::getResultSuccess($message, $actionTemplate);
                break;
        }
        return $result;
    }
    final protected function create_validate_process(array $formDatas): array
    {
        return $formDatas;
    }
    //로그인화면
    public function login_form_process(): void
    {
        $this->sns_buttoh = $this->getSNSButton();
    }
    public function login_form(): RedirectResponse|string
    {
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            $this->getService()->setFormOptions();
            //기본값정의
            $this->getService()->setFormDatas($this->request->getGet());
            $this->login_form_process();
            helper(['form']);
            $this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            return $this->getResultFail($e->getMessage());
        }
    }
    //로그인처리
    public function login(): RedirectResponse|string
    {
        //Transaction Start
        $db = \Config\Database::connect();
        $db->transStart();
        try {
            $this->getService()->setAction(__FUNCTION__);
            $this->getService()->setFormFields();
            $this->getService()->setFormFilters();
            $this->getService()->setFormRules();
            //전달값정의
            $this->getService()->setFormDatas($this->request->getPost());
            $this->doValidations();
            $this->entity = $this->login_process($this->getService()->getFormDatas());
            $db->transCommit();
            return $this->getResultSuccess();
        } catch (\Exception $e) {
            $db->transRollback();
            return $this->getResultFail($e->getMessage());
        }
    }
    //로그아웃
    final public function logout(): RedirectResponse
    {
        try {
            $this->getService()->logout();
            // 홈페이지로 리다이렉트
            return redirect()->route('/')->with('error', MESSAGES['LOGOUT']);
        } catch (\Exception $e) {
            log_message("error", $e->getMessage());
            return redirect()->back()->with('error', "로그아웃 중 오류가 발생했습니다.");
        }
    }
}
