<?php

namespace App\Support\Middleware;

use App\Models\ManagedEnvironment;
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('environment') ?? $request->route()?->parameter('tenant');

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

        $user = $request->user();

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

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

        if ($tenant->isRemovedFromWorkspace()) {
            abort(404);
        }

        if ($tenant->workspace?->isClosed()) {
            abort(404);
        }

        return $next($request);
    }
}
