<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Blocks the request with 403 if the required module is not enabled
 * for the current tenant.
 *
 * Usage in routes:
 *   Route::middleware('module:production')->...
 *   Route::middleware('module:inventory,purchase_orders')->...  (any of)
 */
class CheckModuleEnabled
{
    public function handle(Request $request, Closure $next, string ...$modules): Response
    {
        // If no tenant context, allow through (e.g. public routes)
        if (!app()->bound('current_tenant')) {
            return $next($request);
        }

        $tenant = app('current_tenant');

        foreach ($modules as $module) {
            if ($tenant->hasModule($module)) {
                return $next($request);
            }
        }

        return response()->json([
            'success'    => false,
            'message'    => 'This feature is not enabled for your business plan.',
            'error_code' => 'MODULE_NOT_ENABLED',
            'meta'       => [
                'required_modules' => $modules,
                'business_type'    => $tenant->business_type,
            ],
        ], Response::HTTP_FORBIDDEN);
    }
}
