<?php

namespace App\Http\Middleware;

use App\Facades\UserService;
use App\Http\Response\ResponseJson;
use App\Jobs\AddShareLog;
use App\Models\User;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Support\Facades\Auth;
use Firebase\JWT\JWT;
use Illuminate\Support\Facades\Log;

class Authenticate extends Middleware
{
    use ResponseJson;
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }

    public function handle($request, \Closure $next, ...$guards)
    {
        $is_admin = false;
        if (isset($guards[0]) && $guards[0] == 'admin') {
            $is_admin = true;
//            $this->authenticate($request, $guards);
//            return $next($request);
        }
        $user = null;
        $token = $request->header("Authorization");
        if ($token) {
            $token = str_replace("Bearer ", '', $token);
            try {
                $user = UserService::checkJwtToken($token,$is_admin);
                if ($user) {
//                    $request->merge(['user'=>$user]);
                    Auth::login($user);
                }else {
                    return $this->authFail();
                }
            }catch (\Exception $e) {
                return $this->authFail();
            }
        }else {
            return $this->authFail();
        }
//        $user = auth()->user();
        if ($user && $request->from_user_id && !$is_admin) {
            $data = ['user_id'=>$user->id, 'from_user_id'=>$request->from_user_id, 'from_type'=>$request->from_type, 'from_source'=>'oa'];
            AddShareLog::dispatch($data)->onQueue('health');
        }
        return $next($request);
    }
}
