<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class EnsureModuleEnabled
{
    public function handle(Request $request, Closure $next, string $module)
    {
        $tenantId = app('tenant.id');

        $enabled = DB::table('tenant_modules')
            ->where('tenant_id', $tenantId)
            ->where('module_key', $module)
            ->where('enabled', true)
            ->exists();

        abort_if(! $enabled, 403, 'Module is not enabled for this tenant.');

        return $next($request);
    }
}
