<?php

namespace App\Http\Middleware;

use App\Services\Tenancy\CurrentBusiness;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class ResolveCurrentBusiness
{
    public function handle(Request $request, Closure $next): Response
    {
        $business = app(CurrentBusiness::class)->resolveForRequest($request);

        abort_if(! $business && ! $request->user()?->isSuperAdmin(), 403, 'No business workspace is assigned to this account.');

        $request->attributes->set('current_business', $business);
        View::share('currentBusiness', $business);

        return $next($request);
    }
}
