<?php

namespace App\Services\Security\Captcha;

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

class HcaptchaCaptchaProvider implements CaptchaProviderInterface
{
    public function name(): string
    {
        return 'hcaptcha';
    }

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

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

    public function inputName(): string
    {
        return 'h-captcha-response';
    }

    public function scriptUrl(): string
    {
        return (string) config('services.hcaptcha.script_url', 'https://js.hcaptcha.com/1/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.hcaptcha.timeout', 5))
                ->post((string) config('services.hcaptcha.verify_url', 'https://hcaptcha.com/siteverify'), [
                    'secret' => (string) config('services.hcaptcha.secret', ''),
                    'response' => $token,
                    'remoteip' => $ip,
                ]);

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

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

            return false;
        }
    }
}
