<?php

namespace App\Http\Middleware;

use App\Core\Service\ApiAccessTokenService;
use App\Exceptions\ApiErrorException ;
use Closure;
use Exception;
use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;

use Illuminate\Support\Facades\Config;

class JwtMiddleware
{

    private $apiAccessTokenService;

    public function __construct(
        ApiAccessTokenService $apiAccessTokenService
    )
    {
        $this->apiAccessTokenService = $apiAccessTokenService ;
    }

    public function handle($request, Closure $next, $guard = null)
    {
        $token = $request->header('authToken');

        if (!$token) {
            return apiResponse(0, 'Token not provided.', null, 401);
        }

        try {
            $credentials = JWT::decode($token, Config::get('app.jwt.secret'), ['HS256']);

            $findTokenCriteria = [
                'criteria' => [
                    ['field' => 'token', 'condition' => '=', 'value' => md5($token) ],
                    ['field' => 'expire_date', 'condition' => '>', 'value' => time() ],
                    ['field' => 'user_id', 'condition' => '=', 'value' => $credentials->user_id ],
                    ['field' => 'invalidate', 'condition' => '=', 'value' => 0 ],
                ],
                'firstRow' => 1
            ];
            $getTokenData = $this->apiAccessTokenService->select($findTokenCriteria);
            if(!$getTokenData['data']){
                throw new ExpiredException();
            }

        } catch (ExpiredException $e) {
            return apiResponse(0, lang('Token is expired.'), null, 401);
        } catch (Exception $e) {
            return apiResponse(0, lang('An error while decoding token.'), null, 500);
        }


        $inputs = json_decode($request->getContent(), true);
        $inputs = is_array($inputs) ? $inputs : ["params" => []];

        $user = User::find($credentials->user_id);

        // Now let's put the user in the request class so that you can grab it from there
        $request->credentials = $credentials;
        $request->body = $inputs;
        $request->auth = $user;
        return $next($request);
    }
}
