<?php

namespace Modules\SaasSwitcher\Http\Middleware;

use Closure;

/**
 * Route guard: 403 unless the active business is entitled to the given module.
 *
 * Usage:  Route::middleware('module:VetClinic')->...   (alias registered in
 * SaasSwitcherServiceProvider). This is the route-level counterpart to the
 * menu gates — it blocks direct-URL access to a module a tenant isn't entitled
 * to. DATA-driven (see Modules\SaasSwitcher\Support\ModuleEntitlementService), so the admin
 * Gate::before bypass cannot defeat it.
 */
class EnsureModuleEntitled
{
    public function handle($request, Closure $next, string $module)
    {
        if (! module_entitled($module)) {
            if ($request->expectsJson()) {
                return response()->json(['message' => 'This module is not enabled for your business.'], 403);
            }
            abort(403, 'This module is not enabled for your business.');
        }

        return $next($request);
    }
}
