<?php

declare(strict_types=1);

namespace BotGuard\Services\Captcha;

/**
 * Resolves the active CAPTCHA provider from configuration.
 *
 * The provider is read from config('captcha.provider') (seeded into settings and
 * overridable in the admin panel). Unknown/misconfigured providers fall back to
 * the always-available self-hosted puzzle so verification never breaks.
 */
final class CaptchaManager
{
    public function provider(?string $name = null): CaptchaProviderInterface
    {
        $name = $name ?? (string) config('captcha.provider', 'puzzle');

        return match ($name) {
            'recaptcha' => $this->remote('recaptcha'),
            'hcaptcha'  => $this->remote('hcaptcha'),
            'turnstile' => $this->remote('turnstile'),
            default     => new PuzzleProvider(),
        };
    }

    private function remote(string $provider): CaptchaProviderInterface
    {
        /** @var array{site_key:string, secret:string, verify_url:string} $config */
        $config = (array) config("captcha.{$provider}", []);

        // If keys are not configured, degrade gracefully to the puzzle.
        if (empty($config['secret']) || empty($config['site_key'])) {
            return new PuzzleProvider();
        }

        return new RemoteCaptchaProvider($provider, $config);
    }
}
