<?php

namespace App\Services\Integrations\Sdk;

use App\Models\PlatformConnection;
use App\Services\Integrations\IntegrationTestResult;
use Throwable;

class ApiSdkProbeService
{
    public function __construct(
        private readonly GoogleAdsSdkClientFactory $googleAds,
        private readonly MetaBusinessSdkClient $meta,
        private readonly GoogleApiClientFactory $googleApi,
        private readonly Ga4DataApiClientFactory $ga4,
    ) {}

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

        try {
            return match ($connection->platform) {
                'google_ads' => $this->probeGoogleAds($connection, $started),
                'meta_ads' => $this->probeMeta($connection, $started),
                'search_console' => $this->probeSearchConsole($connection, $started),
                'ga4' => $this->probeGa4($connection, $started),
                default => IntegrationTestResult::failed('SDK probe için desteklenmeyen platform: '.$connection->platform),
            };
        } catch (Throwable $e) {
            return IntegrationTestResult::failed($e->getMessage(), [], null, $this->duration($started));
        }
    }

    private function probeGoogleAds(PlatformConnection $connection, float $started): IntegrationTestResult
    {
        $client = $this->googleAds->make($connection);
        $version = $this->googleAds->versionNamespace();
        $service = $client->getCustomerServiceClient();
        $response = $service->listAccessibleCustomers();

        $resourceNames = [];
        foreach ($response->getResourceNames() as $resourceName) {
            $resourceNames[] = $resourceName;
        }

        return IntegrationTestResult::success('Google Ads SDK bağlantısı başarılı.', [
            'sdk_version_namespace' => $version,
            'total_accessible_customers' => count($resourceNames),
            'resource_names' => array_slice($resourceNames, 0, 10),
        ], null, $this->duration($started));
    }

    private function probeMeta(PlatformConnection $connection, float $started): IntegrationTestResult
    {
        $this->meta->init($connection);
        $adAccountId = $this->meta->normalizedAdAccountId($connection);

        $adAccountClass = 'FacebookAds\\Object\\AdAccount';
        if (! class_exists($adAccountClass)) {
            throw new \RuntimeException('FacebookAds\\Object\\AdAccount sınıfı bulunamadı. SDK kurulumu eksik olabilir.');
        }

        $account = new $adAccountClass($adAccountId);
        $insights = $account->getInsights(
            ['spend', 'impressions', 'clicks', 'cpc', 'cpm', 'ctr', 'date_start', 'date_stop'],
            ['date_preset' => 'yesterday', 'limit' => 1]
        );

        $sample = [];
        foreach ($insights as $row) {
            $sample[] = method_exists($row, 'exportAllData') ? $row->exportAllData() : (array) $row;
        }

        return IntegrationTestResult::success('Meta Business SDK bağlantısı başarılı.', [
            'ad_account_id' => $adAccountId,
            'sample' => $sample[0] ?? [],
        ], null, $this->duration($started));
    }

    private function probeSearchConsole(PlatformConnection $connection, float $started): IntegrationTestResult
    {
        $client = $this->googleApi->make($connection, ['https://www.googleapis.com/auth/webmasters.readonly']);
        $serviceClass = 'Google\\Service\\SearchConsole';
        if (! class_exists($serviceClass)) {
            throw new \RuntimeException('Google\\Service\\SearchConsole sınıfı bulunamadı. google/apiclient kurulumu kontrol edilmeli.');
        }

        $service = new $serviceClass($client);
        $sites = $service->sites->listSites();
        $entries = [];
        foreach ($sites->getSiteEntry() ?? [] as $entry) {
            $entries[] = [
                'siteUrl' => method_exists($entry, 'getSiteUrl') ? $entry->getSiteUrl() : null,
                'permissionLevel' => method_exists($entry, 'getPermissionLevel') ? $entry->getPermissionLevel() : null,
            ];
        }

        return IntegrationTestResult::success('Search Console SDK bağlantısı başarılı.', [
            'total_sites' => count($entries),
            'sites' => array_slice($entries, 0, 10),
        ], null, $this->duration($started));
    }

    private function probeGa4(PlatformConnection $connection, float $started): IntegrationTestResult
    {
        if (! $this->ga4->installed()) {
            throw new \RuntimeException('google/analytics-data kurulu değil.');
        }

        return IntegrationTestResult::success('GA4 Data SDK kurulu. GA4 veri çekimi mevcut OAuth REST akışıyla devam eder; service account kullanılacaksa GOOGLE_APPLICATION_CREDENTIALS tanımlanmalı.', [
            'class' => 'Google\\Analytics\\Data\\V1beta\\Client\\BetaAnalyticsDataClient',
            'google_application_credentials' => env('GOOGLE_APPLICATION_CREDENTIALS') ?: null,
        ], null, $this->duration($started));
    }

    private function duration(float $started): int
    {
        return (int) round((microtime(true) - $started) * 1000);
    }
}
