<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Support\ModuleHelper;
use Closure;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * Middleware: module:<key>
 *
 * Blocks the request with a 403 JSON response when the specified module
 * is disabled in config/modules.php (driven by MODULE_<KEY>_ENABLED env).
 *
 * Usage in routes:
 *   Route::post('/api/pos/start', ..., ['middleware' => 'module:pos']);
 *
 * Or applied to a group:
 *   Route::group(['middleware' => 'module:products'], function () { ... });
 */
class CheckModuleEnabled
{
    /**
     * Handle the incoming request.
     *
     * @param ServerRequestInterface $request
     * @param Closure $next
     * @param string $moduleKey  The module key from config/modules.php
     * @return ResponseInterface|mixed
     */
    public function handle($request, Closure $next, string $moduleKey = '')
    {
        if ($moduleKey && ModuleHelper::isDisabled($moduleKey)) {
            $label = ModuleHelper::getLabel($moduleKey);

            return response()->json([
                'success' => false,
                'message' => "The \"{$label}\" module is currently disabled.",
                'module'  => $moduleKey,
                'code'    => 'MODULE_DISABLED',
            ], 403);
        }

        return $next($request);
    }
}
