<?php

namespace App\Http\Middleware;

use App\Services\Response\ResponseService;
use Closure;
use Illuminate\Support\Facades\Auth;
use Modules\User\Models\User;

class ApiTokenMiddleware
{


    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $token = $request->bearerToken() ?? $request->header('token');
        request()->merge(['api_token' => $token]);

        if (!$token) {
            $response = [
                'status' => 401,
                'message' => 'Unauthenticated'
            ];
            return ResponseService::response($response);
        }
        // Check token exist in DB
        $user = User::where('api_token', $token)->whereIn('role', [4, 6])->first();

        if (!$user) {
            $response = [
                'status' => 401,
                'message' => 'Unauthenticated'
            ];
            return ResponseService::response($response);
        }

        Auth::login($user);


        return $next($request);
    }

}
