<?php

namespace App\Http\Middleware\Manager;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Validation\UnauthorizedException;
use App\Http\Helpers\Api\Helpers;



class ApiAuthenticator
{
     /**
     * Determine if the user is authenticated and authorized to access the requested resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  array  $guards
     * @return void
     *
     * @throws \Illuminate\Auth\AuthenticationException
     * @throws \Illuminate\Validation\UnauthorizedException
     */
    protected function authenticate($request, array $guards)
    {
        if (auth()->guard('manager_api')->check()) {

            return auth()->shouldUse('manager_api');
        }

        throw new UnauthorizedException('sorry');
    }

   /**
     * Handle an unauthenticated user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  array  $guards
     * @return \Illuminate\Http\JsonResponse
     *
     * @throws \Illuminate\Validation\UnauthorizedException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        try {
            $this->authenticate($request, $guards);
        } catch (UnauthorizedException $e) {
            $message = ['error'=>[__("Sorry, You are not authorized Manager")]];
            return Helpers::unauthorized( $message);
        }

        return $next($request);
    }
}
