<?php

namespace App\Http\Middleware;

use App\Services\Response\ResponseService;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Exceptions\HttpResponseException;
use App\Models\User;
use Modules\User\Services\UserService;

class StrictAuthApi
{
    public function __construct(
        private UserService $userService
    ){}
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $res = false;
        $token= $request->bearerToken();

        if($token)
        {
            $user = $this->userService->getItemByToken($token);
            if($user)
            {
                Auth::login($user);
                $this->userService->update
                ([
                    'device_token'=>$request->header('tokenDevice'),
                    'language'=>getCurrentLocale()
                ],$user->id);
                $res = true;
            }
        }
        if($res == false)
        {
            ResponseService::responseFail(__('web.login_first'));
        }
        return $next($request);
    }
}
