<?php

declare(strict_types=1);

namespace Builder\Core\Foundation\Middleware;

use Builder\Core\Exceptions\UnauthorizedAccessException;
use Builder\Core\Foundation\Contracts\BuilderAccessible;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

final class BuilderAuth
{
    public static function guard(): string
    {
        return (string) config('builder.auth.guard', 'web');
    }

    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user(self::guard());

        if (! $user) {
            return to_route('builder.login');
        }

        if (! ($user instanceof BuilderAccessible) || ! $user->canAccessBuilder()) {
            throw new UnauthorizedAccessException('Unauthorized.');
        }

        return $next($request);
    }
}
