<?php

namespace App\Services\Security\Captcha;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class RecaptchaCaptchaProvider implements CaptchaProviderInterface
{
    public function name(): string
    {
        return 'recaptcha';
    }

    public function isEnabled(): bool
    {
        return (bool) config('services.recaptcha.enabled', false)
            && $this->siteKey() !== ''
            && (string) config('services.recaptcha.secret', '') !== '';
    }

    public function siteKey(): string
    {
        return (string) config('services.recaptcha.site_key', '');
    }

    public function inputName(): string
    {
        return 'g-recaptcha-response';
    }

    public function scriptUrl(): string
    {
        return (string) config('services.recaptcha.script_url', 'https://www.google.com/recaptcha/api.js');
    }

    public function verify(string $token, ?string $ip = null): bool
    {
        if (! $this->isEnabled()) {
            return true;
        }

        if (trim($token) === '') {
            return false;
        }

        try {
            $response = Http::asForm()
                ->timeout((int) config('services.recaptcha.timeout', 5))
                ->post((string) config('services.recaptcha.verify_url', 'https://www.google.com/recaptcha/api/siteverify'), [
                    'secret' => (string) config('services.recaptcha.secret', ''),
                    'response' => $token,
                    'remoteip' => $ip,
                ]);

            if ($response->failed()) {
                return false;
            }

            return (bool) data_get($response->json(), 'success', false);
        } catch (\Throwable $exception) {
            Log::warning('recaptcha verification request failed', [
                'message' => $exception->getMessage(),
            ]);

            return false;
        }
    }
}
