<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\api\controller;

use app\BaseController;
use app\service\AuthService;
use think\Request;


/**
 * C端控制器基类
 * 提供用户认证辅助方法
 * @package app\api\controller
 */
abstract class BaseApiController extends BaseController
{
    /**
     * 获取可选的用户ID
     * 优先从请求属性获取，其次从 Authorization Bearer Token 解析
     * @param Request $request
     * @return int
     */
    protected function getOptionalUid(Request $request): int
    {
        $uid = (int)($request->uid ?? 0);
        if ($uid > 0) {
            return $uid;
        }

        $token = $request->header('Authorization', '');
        if (strpos($token, 'Bearer ') === 0) {
            $payload = AuthService::validateToken(substr($token, 7));
            return (int)($payload['uid'] ?? 0);
        }

        return 0;
    }
}
