<?php

namespace App\Http\Middleware;

use App\Constants\HttpStatus;
use App\Models\Admin;
use Closure;
use App\Services\JwtService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class JwtAdminMiddleware
{
    protected $jwtService;

    public function __construct(JwtService $jwtService)
    {
        $this->jwtService = $jwtService;
    }

    public function handle(Request $request, Closure $next)
    {
        $authHeader = $request->header('Authorization');
        if (empty($authHeader)) {
            $code = HttpStatus::AUTHORIZATION_HEADER_NOT_FOUND;
            return response()->json([
                'code' => $code,
                'timestamp' => time(),
                'msg' => __('messages.' . $code),
                'data' => []
            ]);
        }
        $token = str_replace('Bearer ', '', $authHeader);
        $user = $this->jwtService->validateToken($token);
        if ($user) {
            $request->user = Admin::findOrFail($user->user_id);

            //单点登录
//            $oldToken = Cache::get("user_{$request->user->getId()}_jwt");
//            if ($oldToken !== $token) {
//                $code = HttpStatus::AUTHORIZATION_HEADER_NOT_FOUND;
//                return response()->json([
//                    'code' => $code,
//                    'timestamp' => time(),
//                    'msg' => __('messages.' . $code),
//                    'data' => []
//                ]);
//            }
            return $next($request);
        }
        $code = HttpStatus::AUTHORIZATION_HEADER_NOT_FOUND;
        return response()->json([
            'code' => $code,
            'timestamp' => time(),
            'msg' => __('messages.' . $code),
            'data' => []
        ]);
    }
}