<?php

namespace App\Http\Middleware;

use App\Services\Subscription\ModuleAccessService;
use App\Support\Tenant;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Uso en rutas: ->middleware('module:bookings')
 * o ->middleware('module:bookings,reports') para exigir cualquiera de varios.
 */
class EnsureModuleIsEnabled
{
    public function __construct(protected ModuleAccessService $access) {}

    public function handle(Request $request, Closure $next, string ...$modules): Response
    {
        $company = Tenant::current();

        if (! $company) {
            return $next($request);
        }

        foreach ($modules as $module) {
            if ($this->access->isEnabled($company, $module)) {
                return $next($request);
            }
        }

        if ($request->expectsJson()) {
            abort(403, 'Módulo no disponible en tu plan.');
        }

        return redirect()->route('tenant.dashboard')
            ->with('error', 'Esta funcionalidad no está incluida en tu plan actual.');
    }
}
