<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Model\User;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;
use Qbhy\HyperfAuth\AuthManager;

abstract class AbstractController
{
    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected ResponseInterface $response;

    /**
     * 统一获取当前认证用户
     *
     * 优先从 request attribute 获取（JWT/API Key 中间件统一设置），
     * 兜底通过 JWT guard 获取（过渡期兼容）。
     */
    protected function getAuthUser(): ?User
    {
        $user = $this->request->getAttribute('auth_user');
        if ($user instanceof User) {
            return $user;
        }

        // 兜底：直接通过 JWT guard 获取
        try {
            $auth = $this->container->get(AuthManager::class);
            $user = $auth->guard('jwt')->user();
            return $user instanceof User ? $user : null;
        } catch (\Throwable) {
            return null;
        }
    }
}
