<?php

namespace App\Http\Middleware;

use App\Exceptions\UnauthorizedException;
use App\Gates\UserGate;
use App\Repos\UserRepo;
use App\Services\ResponseService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

class AuthMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        try {
            $token = $request->bearerToken();
            if (!$token) throw new UnauthorizedException();
            $user = UserRepo::firstByAuthToken($token);
            if (!$user) throw new UnauthorizedException();
            UserGate::canAuth($user);
            Auth::loginUsingId($user->id);
            return $next($request);
        } catch (Throwable $error) {
            return ResponseService::handleError($error);
        }
    }
}
