<?php

namespace App\Services\Captcha\Providers;

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

class TrustIPProvider implements CaptchaProviderInterface
{
    protected string $apiKey;
    protected string $verifyUrl;
    protected string $scriptUrl;

    public function __construct(array $config)
    {
        $this->apiKey = $config['api_key'] ?? '';
        $this->verifyUrl = $config['verify_url'] ?? 'https://api.trustip.io/v1/verify';
        $this->scriptUrl = $config['script_url'] ?? 'https://cdn.trustip.io/trustip.js';
    }

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

            $httpResponse = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ])->post($this->verifyUrl, [
                'token' => $response,
                'ip' => $ipAddress,
            ]);

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

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

            $result = $httpResponse->json();

            return [
                'success' => $result['success'] ?? false,
                'score' => $result['score'] ?? null,
                'error' => $result['error'] ?? null,
                'response_time' => $responseTime,
                'metadata' => $result,
            ];

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

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

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

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

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

    public function render(array $attributes = []): string
    {
        $attrs = array_merge([
            'class' => 'trustip-captcha',
            'data-apikey' => $this->apiKey,
        ], $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->apiKey);
    }

    public function getApiKey(): string
    {
        return $this->apiKey;
    }
}
