<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Crypt;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;
use Symfony\Component\HttpFoundation\Response;

class AuthenticateWithJWT
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        try {
            // $user = JWTAuth::parseToken()->authenticate();
            $encryptedToken = Cookie::get('api_token');
            $token = Crypt::decryptString($encryptedToken);
            $parts = explode('|', $token);
            $token = $parts[1];
            // $userData = JWTAuth::setToken($token)->getPayload();
        } catch (\Exception $e) {

            return response()->json(['error' => 'Unauthorized'], 401);
        }
        // $uuidFromToken = $userData->get('uuid');
        $userFromDatabase = User::where('api_token', $token)->first();

        if (!$userFromDatabase) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        if ($userFromDatabase->api_token !== $token) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        $request->merge(['user' => $userFromDatabase]);

        return $next($request);

    }
    public function decodeToken($token)
    {
        return JWT::decode($token, new Key(env('JWT_SECRET'), 'HS256'));
    }
}
