<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\Response;

class EnsurePlatformCapability
{
    /**
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $capability): Response
    {
        $capability = trim($capability);

        if ($capability === '') {
            return $next($request);
        }

        $user = auth('platform')->user();

        if ($user === null) {
            return $next($request);
        }

        if (! Gate::forUser($user)->allows($capability)) {
            abort(403);
        }

        return $next($request);
    }
}
