<?php

namespace App\Services\Integrations;

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

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

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

        try {
            $accessToken = $this->oauth->accessTokenFromRefreshToken($connection);
            $endpoint = 'https://analyticsadmin.googleapis.com/v1beta/accountSummaries';
            $response = Http::withToken($accessToken)->timeout(45)->get($endpoint, ['pageSize' => 20]);
            $duration = (int) round((microtime(true) - $started) * 1000);

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

            $summaries = $response->json('accountSummaries') ?? [];

            return IntegrationTestResult::success('GA4 bağlantısı başarılı. Erişilebilir hesap özeti sayısı: '.count($summaries), [
                'account_summaries' => array_slice($summaries, 0, 5),
                'total_summaries' => count($summaries),
            ], $response->status(), $duration);
        } catch (\Throwable $e) {
            $duration = (int) round((microtime(true) - $started) * 1000);
            return IntegrationTestResult::failed($e->getMessage(), [], null, $duration);
        }
    }
}
