<?php

namespace app\middleware;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\Request;
use think\Response;

/**
 * 管理员认证中间件
 */
class AdminAuth
{
    /**
     * 处理请求
     */
    public function handle(Request $request, \Closure $next)
    {
        $token = $request->header('Authorization');

        if (empty($token)) {
            return json([
                'code' => 401,
                'msg' => '未提供认证令牌'
            ], 401);
        }

        // 移除 "Bearer " 前缀
        if (strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        try {
            $secretKey = env('jwt.secret_key', 'your-super-secret-key-change-in-production-32chars!');
            $algorithm = env('jwt.algorithm', 'HS256');

            $decoded = JWT::decode($token, new Key($secretKey, $algorithm));
            $payload = (array)$decoded;

            // 将管理员信息存入请求
            $request->adminUser = [
                'id' => $payload['sub'],
                'username' => $payload['username'],
            ];

            return $next($request);
        } catch (\Exception $e) {
            return json([
                'code' => 401,
                'msg' => '无效的认证令牌'
            ], 401);
        }
    }
}