<?php

declare(strict_types=1);

namespace app\common\controller;

use app\common\library\Auth;
use app\common\library\token\TokenExpirationException;
use support\Response;
use Webman\Http\Request as WebmanRequest;

/**
 * 前台/会员中心控制器基类
 * 继承 Api，增加会员鉴权
 */
class Frontend extends Api
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];
    protected ?Auth $auth = null;

    /**
     * 前台初始化（需在控制器方法开头调用）
     * @return Response|null 若需直接返回则返回 Response，否则 null
     */
    public function initializeFrontend(WebmanRequest $request): ?Response
    {
        $response = $this->initializeApi($request);
        if ($response !== null) return $response;

        $this->setRequest($request);
        $path = trim($request->path(), '/');
        $parts = explode('/', $path);
        $action = $parts[array_key_last($parts)] ?? '';
        $needLogin = !action_in_arr($this->noNeedLogin, $action);

        try {
            $this->auth = Auth::instance();
            $token = get_auth_token(['ba', 'user', 'token'], $request);
            if ($token) $this->auth->init($token);
        } catch (TokenExpirationException) {
            if ($needLogin) return $this->error(__('Token expiration'), [], 409);
        }

        if ($needLogin) {
            if (!$this->auth->isLogin()) {
                return $this->error(__('Please login first'), ['type' => Auth::NEED_LOGIN], Auth::LOGIN_RESPONSE_CODE);
            }
            if (!action_in_arr($this->noNeedPermission, $action)) {
                $routePath = get_controller_path($request) . '/' . $action;
                if (!$this->auth->check($routePath)) {
                    return $this->error(__('You have no permission'), [], 401);
                }
            }
        }

        event_trigger('frontendInit', $this->auth);
        return null;
    }
}
