<?php

namespace App\Controllers\Auth;

use App\Controllers\CommonController;

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
{
    private $_helper = null;
    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;
    final public function getHelper(): mixed
    {
        if (!$this->_helper) {
            $this->_helper = new AuthHelper();
        }
        return $this->_helper;
    }
    protected function getResultFail_process(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_process(string $message = MESSAGES["SUCCESS"], ?string $actionTemplate = null): RedirectResponse|string
    {
        switch ($this->getAction()) {
            case 'create': //Login처리
                $result = redirect()->to($this->getMyAuth()->popPreviousUrl())->with('error', $message);
                break;
            default:
                $result = parent::getResultSuccess_process($message, $actionTemplate);
                break;
        }
        return $result;
    }
    final protected function create_validate_process(array $formDatas): array
    {
        return $formDatas;
    }
    //로그인화면
    public function create_form_process(): void
    {
        $this->sns_buttoh = $this->getSNSButton();
    }
    //로그아웃
    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', "로그아웃 중 오류가 발생했습니다.");
        }
    }
}
