<?php

namespace App\Http\Middleware;

use App\Domain\Shared\Services\SettingsService;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Self-registration is off unless an academy has deliberately turned it on.
 *
 * This is the one route group in the product where a stranger writes into
 * `people` and `participants`, so it does not become reachable because a deploy
 * happened. Every tenant gets the code and nobody gets the open form until
 * somebody decides.
 *
 * 404, not 403: a disabled feature should be indistinguishable from a feature
 * that does not exist. A 403 advertises that there is a signup form here and
 * invites someone to find the setting.
 */
class EnsureSelfRegistrationEnabled
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! app()->has('current_academy')) {
            abort(404);
        }

        $enabled = app(SettingsService::class)->get('portal.self_registration_enabled', false);

        abort_unless(filter_var($enabled, FILTER_VALIDATE_BOOLEAN), 404);

        return $next($request);
    }
}
