<?php


namespace App\Http\Middleware;

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

class JwtMiddleware
{
    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 = User::findOrFail($user->user_id);
            $oldToken = Cache::get("user_{$request->user->id}_jwt");
            if ($oldToken !== $token) {
                $code = HttpStatus::USER_ANOTHER_DEVICE;
                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' => []
        ]);
    }
}
