<?php

namespace App\Http\Middleware;

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

/**
 * Middleware to ensure a required module is installed and enabled
 *
 * Usage: Route::middleware(['module:AIAgentFramework'])
 */
class RequireModule
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     * @param  string  $module  The module name to check
     */
    public function handle(Request $request, Closure $next, string $module): Response
    {
        // Check if module exists and is enabled
        if (!moduleExists($module)) {
            // For API requests, return JSON error
            if ($request->expectsJson() || $request->is('api/*')) {
                return response()->json([
                    'success' => false,
                    'message' => "The {$module} module is not available. Please contact your administrator.",
                    'error_code' => 'MODULE_NOT_FOUND'
                ], 404);
            }

            // For web requests, abort with 404
            abort(404, "The {$module} module is not available. Please contact your administrator.");
        }

        return $next($request);
    }
}
