<?php

declare(strict_types=1);

namespace Bongo\Builder\Http\Controllers\Api;

use Bongo\Framework\Http\Controllers\AbstractApiController;
use Illuminate\Http\Request;

class ValidationController extends AbstractApiController
{
    protected const DEFAULT_NAME = 'enquiry';

    protected const NAME_PATTERN = '/^[A-Za-z0-9_-]{1,50}$/';

    public function index(Request $request)
    {
        $name = $this->captchaAction($request);

        return view('builder::api.validation', compact('name'))->render();
    }

    /**
     * The name becomes the captcha action and is interpolated straight into the widget
     * markup, so anything but a plain key falls back to the default rather than being
     * reflected. This route is public.
     */
    protected function captchaAction(Request $request): string
    {
        $name = (string) $request->query('name', static::DEFAULT_NAME);

        if (! preg_match(static::NAME_PATTERN, $name)) {
            return static::DEFAULT_NAME;
        }

        return $name;
    }
}
