<?php

namespace App\Services\Integrations;

use App\Models\PlatformConnection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class SearchConsoleApiService
{
    public function __construct(private readonly GoogleOAuthService $oauth) {}

    public function test(PlatformConnection $connection): IntegrationTestResult
    {
        $started = microtime(true);

        try {
            $accessToken = $this->oauth->accessTokenFromRefreshToken($connection);
            $endpoint = 'https://www.googleapis.com/webmasters/v3/sites';
            $response = Http::withToken($accessToken)->timeout(45)->get($endpoint);
            $duration = (int) round((microtime(true) - $started) * 1000);

            if (! $response->successful()) {
                return IntegrationTestResult::failed('Search Console bağlantı testi başarısız: '.Str::limit($response->body(), 700), $response->json() ?: [], $response->status(), $duration);
            }

            $sites = $response->json('siteEntry') ?? [];

            return IntegrationTestResult::success('Search Console bağlantısı başarılı. Erişilebilir mülk sayısı: '.count($sites), [
                'sites' => array_slice($sites, 0, 10),
                'total_sites' => count($sites),
            ], $response->status(), $duration);
        } catch (\Throwable $e) {
            $duration = (int) round((microtime(true) - $started) * 1000);
            return IntegrationTestResult::failed($e->getMessage(), [], null, $duration);
        }
    }
}
