<?php

namespace App\Support\Middleware;

use App\Models\Tenant;
use App\Models\User;
use App\Services\Auth\CapabilityResolver;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class DenyNonMemberTenantAccess
{
    /**
     * @param  Closure(Request): Response  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $tenant = $request->route()?->parameter('tenant');

        if (! $tenant instanceof Tenant) {
            return $next($request);
        }

        $user = $request->user();

        if (! $user instanceof User) {
            return $next($request);
        }

        if (! app(CapabilityResolver::class)->isMember($user, $tenant)) {
            abort(404);
        }

        return $next($request);
    }
}
