<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\controller\Frontend;
use app\common\facade\Token;
use support\Response;
use Webman\Http\Request;
use function response;

abstract class MobileBase extends Frontend
{
    protected array $noNeedPermission = ['*'];
    protected array $noNeedAuthToken = [];

    /**
     * 移动端统一初始化：
     * - 校验请求头 auth-token
     * - 再走会员中心 Frontend 初始化（登录态/权限等）
     */
    protected function initializeMobile(Request $request): ?Response
    {
        $this->setRequest($request);

        $path = trim($request->path(), '/');
        $parts = explode('/', $path);
        $action = $parts[array_key_last($parts)] ?? '';
        $needAuthToken = !action_in_arr($this->noNeedAuthToken, $action);
        if ($needAuthToken) {
            $authToken = trim((string) $request->header('auth-token', ''));
            if ($authToken === '') {
                return $this->mobileError(1101, 'Missing auth-token');
            }
            $tokenData = Token::get($authToken);
            $type = $tokenData['type'] ?? '';
            $expireTime = $tokenData['expire_time'] ?? 0;
            if ($type !== 'auth-token' || !is_numeric($expireTime) || $expireTime < time()) {
                return $this->mobileError(1101, 'auth-token is invalid or expired');
            }
        }

        return $this->initializeFrontend($request);
    }

    protected function mobileSuccess(array $data = [], string $message = 'ok'): Response
    {
        if ($message === '') {
            $message = __('ok');
        } else {
            $message = __($message);
        }
        $payload = [
            'code' => 1,
            'message' => $message,
            'data' => $data,
        ];
        return response(json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 200, ['Content-Type' => 'application/json']);
    }

    protected function mobileError(int $code, string $message, array $data = []): Response
    {
        $payload = [
            'code' => $code,
            'message' => __($message),
            'data' => $data,
        ];
        return response(json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 200, ['Content-Type' => 'application/json']);
    }
}

