<?php

namespace DariusMure\Captcha\Services\Providers;

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

class ReCaptchaV3Provider implements CaptchaProviderInterface
{
    protected string $siteKey;
    protected string $secretKey;
    protected string $verifyUrl;
    protected string $scriptUrl;
    protected float $threshold;

    public function __construct(array $config)
    {
        $this->siteKey = $config['site_key'] ?? '';
        $this->secretKey = $config['secret_key'] ?? '';
        $this->verifyUrl = $config['verify_url'] ?? 'https://www.google.com/recaptcha/api/siteverify';
        $this->scriptUrl = $config['script_url'] ?? 'https://www.google.com/recaptcha/api.js';
        $this->threshold = $config['threshold'] ?? 0.5;
    }

    public function verify(string $response, ?string $ipAddress = null): array
    {
        try {
            $startTime = microtime(true);

            $data = [
                'secret' => $this->secretKey,
                'response' => $response,
            ];

            if ($ipAddress) {
                $data['remoteip'] = $ipAddress;
            }

            $httpResponse = Http::asForm()->post($this->verifyUrl, $data);

            $responseTime = (int) ((microtime(true) - $startTime) * 1000);

            if (!$httpResponse->successful()) {
                return [
                    'success' => false,
                    'score' => null,
                    'error' => 'HTTP request failed',
                    'response_time' => $responseTime,
                ];
            }

            $result = $httpResponse->json();
            $score = $result['score'] ?? 0.0;

            return [
                'success' => ($result['success'] ?? false) && $score >= $this->threshold,
                'score' => $score,
                'error' => isset($result['error-codes']) ? implode(', ', $result['error-codes']) : null,
                'response_time' => $responseTime,
                'metadata' => $result,
            ];

        } catch (\Exception $e) {
            Log::error('reCAPTCHA v3 verification failed: ' . $e->getMessage());

            return [
                'success' => false,
                'score' => null,
                'error' => $e->getMessage(),
                'response_time' => 0,
            ];
        }
    }

    public function getName(): string
    {
        return 'recaptcha_v3';
    }

    public function getSiteKey(): string
    {
        return $this->siteKey;
    }

    public function getScriptUrl(): string
    {
        return $this->scriptUrl . '?render=' . $this->siteKey;
    }

    public function render(array $attributes = []): string
    {
        $action = $attributes['data-action'] ?? 'submit';

        // reCAPTCHA v3 is invisible and requires JavaScript
        return sprintf(
            '<input type="hidden" name="g-recaptcha-response" id="g-recaptcha-response-v3" data-action="%s">',
            htmlspecialchars($action)
        );
    }

    public function isConfigured(): bool
    {
        return !empty($this->siteKey) && !empty($this->secretKey);
    }

    public function getThreshold(): float
    {
        return $this->threshold;
    }
}
