<?php

namespace App\Middleware;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Psr7\Response;
use App\Utils\JWTUtil;

class AuthMiddleware
{
    public function __invoke(Request $request, RequestHandler $handler): Response
    {
        $authHeader = $request->getHeaderLine('Authorization');

        if (empty($authHeader)) {
            $response = new Response();
            $response->getBody()->write(json_encode([
                'code' => 401,
                'message' => '未提供认证令牌',
                'data' => null
            ]));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(401);
        }

        // 提取 token (Bearer token)
        $token = str_replace('Bearer ', '', $authHeader);

        $decoded = JWTUtil::decode($token);

        if ($decoded === null) {
            $response = new Response();
            $response->getBody()->write(json_encode([
                'code' => 401,
                'message' => '无效或过期的令牌',
                'data' => null
            ]));
            return $response->withHeader('Content-Type', 'application/json')->withStatus(401);
        }

        // 将用户信息添加到请求属性中
        $request = $request->withAttribute('userId', $decoded['userId']);
        $request = $request->withAttribute('username', $decoded['username']);

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