<?php

declare(strict_types=1);

namespace App\Middleware;

use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Qbhy\HyperfAuth\AuthManager;
use Qbhy\HyperfAuth\Exception\UnauthorizedException;

class AuthMiddleware implements MiddlewareInterface
{
    public function __construct(
        protected AuthManager $auth,
        protected HttpResponse $response
    ) {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            // 验证 token
            $user = $this->auth->guard('jwt')->user();

            if (!$user) {
                return $this->response->json([
                    'code' => 401,
                    'message' => '未授权，请先登录',
                ])->withStatus(401);
            }

            // @attention check here!
            // 检查用户状态
            if (method_exists($user, '__get') && $user->status !== 1) {
                return $this->response->json([
                    'code' => 403,
                    'message' => '账号已被禁用',
                ])->withStatus(403);
            }
        } catch (UnauthorizedException $e) {
            return $this->response->json([
                'code' => 401,
                'message' => 'Token 无效或已过期',
            ])->withStatus(401);
        } catch (\Throwable $e) {
            return $this->response->json([
                'code' => 500,
                'message' => '认证失败: ' . $e->getMessage(),
            ])->withStatus(500);
        }

        return $handler->handle($request);
    }
}
