<?php

declare(strict_types=1);

namespace Maestro\Core\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;
use Maestro\Core\Models\MaestroModule;
use Symfony\Component\HttpFoundation\Response;

/**
 * Blocks requests when the given Maestro module slug is off in {@see MaestroModule}.
 * Superadmin module toggles then control API access like navigation and SPA guards.
 */
final class EnsureMaestroModuleEnabled
{
    /**
     * @param  Closure(Request): Response  $next
     */
    public function handle(Request $request, Closure $next, string $slug): Response
    {
        if (! Schema::hasTable('maestro_modules')) {
            return $next($request);
        }

        $slug = trim($slug);
        if ($slug === '') {
            return $next($request);
        }

        $enabled = Cache::remember(
            'maestro_module:'.$slug,
            60,
            fn (): mixed => MaestroModule::query()->where('slug', $slug)->value('is_enabled'),
        );

        if ($enabled !== true) {
            abort(403, 'This module is disabled.');
        }

        return $next($request);
    }
}
