<?php

namespace DariusMure\Captcha\Services\Providers;

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

class TurnstileProvider implements CaptchaProviderInterface
{
    protected string $siteKey;
    protected string $secretKey;
    protected string $verifyUrl;
    protected string $scriptUrl;

    public function __construct(array $config)
    {
        $this->siteKey = $config['site_key'] ?? '';
        $this->secretKey = $config['secret_key'] ?? '';
        $this->verifyUrl = $config['verify_url'] ?? 'https://challenges.cloudflare.com/turnstile/v0/siteverify';
        $this->scriptUrl = $config['script_url'] ?? 'https://challenges.cloudflare.com/turnstile/v0/api.js';
    }

    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();

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

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

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

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

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

    public function getScriptUrl(): string
    {
        return $this->scriptUrl;
    }

    public function render(array $attributes = []): string
    {
        $attrs = array_merge([
            'class' => 'cf-turnstile',
            'data-sitekey' => $this->siteKey,
        ], $attributes);

        $attrString = '';
        foreach ($attrs as $key => $value) {
            $attrString .= sprintf(' %s="%s"', $key, htmlspecialchars($value));
        }

        return sprintf('<div%s></div>', $attrString);
    }

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