<?php

namespace App\Http\Middleware;

use App\Core\Service\PropertyWebService;
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 MyWebTokenMiddleware
{

    private $propertyWebService;

    public function __construct(
        PropertyWebService $propertyWebService
    )
    {
        $this->propertyWebService = $propertyWebService ;
    }

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

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

        try {

            $findTokenCriteria = [
                'criteria' => [
                    ['field' => 'token', 'condition' => '=', 'value' =>  $token],
                ],
                'firstRow' => 1
            ];
            $getTokenData = $this->propertyWebService->select($findTokenCriteria);

            if(!$getTokenData['data']){
                throw new ExpiredException();
            }

        } catch (ExpiredException $e) {
            return apiResponse(0, lang('Token is expired.'), null, 400);
        } 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" => []];
        $inputs['params']['property_id'] = $getTokenData['data']['property_id'];
        $inputs['params']['property_web_id'] = $getTokenData['data']['id'];
        $inputs['params']['domain'] = $getTokenData['data']['domain'];
        $inputs['params']['default_language'] = $getTokenData['data']['default_language'];
        $inputs['params']['template_id'] = $getTokenData['data']['template_id'];
        $request->body = $inputs;

        return $next($request);
    }
}
