<?php

namespace App\Http\Middleware;

use Closure;
use App\Models\Module;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckModuleActive
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string $moduleName): Response
    {
        $module = Module::where('name', $moduleName)->first();

        if (! $module || ! $module->isActive()) {

            // 🔹 For API routes
            if ($request->expectsJson()) {
                return response()->json([
                    'message' => 'This feature is currently disabled or not available.',
                    'feature' => $moduleName,
                ], 403);
            }

            // 🔹 For Web routes
            abort(403, "The '{$moduleName}' feature is disabled.");
        }

        return $next($request);
    }
}
