<?php

namespace App\Services;

use App\Models\SiteSetting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class VirusTotalService
{
    protected string $baseUrl = 'https://www.virustotal.com/api/v3';

    protected function apiKey(): ?string
    {
        return SiteSetting::get('virustotal_api_key');
    }

    public function isEnabled(): bool
    {
        return SiteSetting::isEnabled('virustotal_enabled') && !empty($this->apiKey());
    }

    public function scan(string $filePath): array
    {
        $apiKey = $this->apiKey();

        if (empty($apiKey)) {
            return ['error' => 'no_api_key', 'message' => 'VirusTotal API key tanımlı değil.'];
        }

        try {
            $response = Http::withHeaders([
                'x-apikey' => $apiKey,
            ])->attach(
                'file',
                file_get_contents($filePath),
                basename($filePath)
            )->post("{$this->baseUrl}/files");

            if ($response->status() === 429) {
                return ['error' => 'rate_limit', 'message' => 'Günlük VirusTotal API limiti doldu.'];
            }

            if (!$response->successful()) {
                return ['error' => 'api_error', 'message' => 'VirusTotal API hatası: ' . $response->status()];
            }

            $data = $response->json();
            return [
                'success'     => true,
                'analysis_id' => $data['data']['id'] ?? null,
            ];
        } catch (\Exception $e) {
            Log::error('VirusTotal scan error: ' . $e->getMessage());
            return ['error' => 'exception', 'message' => $e->getMessage()];
        }
    }

    public function getResult(string $analysisId): array
    {
        $apiKey = $this->apiKey();

        try {
            $response = Http::withHeaders([
                'x-apikey' => $apiKey,
            ])->get("{$this->baseUrl}/analyses/{$analysisId}");

            if ($response->status() === 429) {
                return ['error' => 'rate_limit', 'message' => 'Günlük VirusTotal API limiti doldu.'];
            }

            if (!$response->successful()) {
                return ['error' => 'api_error', 'message' => 'VirusTotal API hatası: ' . $response->status()];
            }

            return ['success' => true, 'data' => $response->json()];
        } catch (\Exception $e) {
            Log::error('VirusTotal getResult error: ' . $e->getMessage());
            return ['error' => 'exception', 'message' => $e->getMessage()];
        }
    }

    public function isLimitExceeded(array $response): bool
    {
        return isset($response['error']) && $response['error'] === 'rate_limit';
    }

    public function isClean(array $result): bool
    {
        $stats = $result['data']['attributes']['stats'] ?? [];
        $malicious  = $stats['malicious'] ?? 0;
        $suspicious = $stats['suspicious'] ?? 0;
        return ($malicious + $suspicious) === 0;
    }

    public function waitForResult(string $analysisId, int $maxAttempts = 10, int $sleepSeconds = 6): array
    {
        for ($i = 0; $i < $maxAttempts; $i++) {
            sleep($sleepSeconds);
            $result = $this->getResult($analysisId);

            if (isset($result['error'])) {
                return $result;
            }

            $status = $result['data']['data']['attributes']['status'] ?? 'queued';

            if ($status === 'completed') {
                return ['success' => true, 'data' => $result['data']['data']];
            }
        }

        return ['error' => 'timeout', 'message' => 'VirusTotal analiz zaman aşımına uğradı.'];
    }
}