<?php

namespace App\Services\Integrations;

use App\Models\PlatformConnection;
use App\Services\Credentials\CredentialVault;

class PlatformConnectionTester
{
    public function __construct(
        private readonly GoogleAdsApiService $googleAds,
        private readonly MetaMarketingApiService $meta,
        private readonly SearchConsoleApiService $searchConsole,
        private readonly Ga4ApiService $ga4,
        private readonly ApiRequestLogger $logger,
        private readonly CredentialVault $vault,
    ) {}

    public function test(PlatformConnection $connection): IntegrationTestResult
    {
        $result = match ($connection->platform) {
            'google_ads' => $this->googleAds->test($connection),
            'meta_ads' => $this->meta->test($connection),
            'search_console' => $this->searchConsole->test($connection),
            'ga4' => $this->ga4->test($connection),
            default => IntegrationTestResult::failed('Desteklenmeyen platform: '.$connection->platform),
        };

        $connection->update([
            'status' => $result->ok ? 'active' : 'error',
            'last_error' => $result->ok ? null : $result->message,
            'last_sync_at' => $result->ok ? now() : $connection->last_sync_at,
            'meta' => array_merge($connection->meta ?? [], [
                'last_test_at' => now()->toIso8601String(),
                'last_test_result' => $result->ok ? 'success' : 'error',
                'last_test_data' => $result->data,
            ]),
        ]);

        $this->vault->markChecked($connection->secureCredential, $result->ok ? null : $result->message);
        $this->logger->log($connection, $this->endpointLabel($connection->platform), 'GET', $result);

        return $result;
    }

    private function endpointLabel(string $platform): string
    {
        return match ($platform) {
            'google_ads' => 'customers:listAccessibleCustomers',
            'meta_ads' => 'ad_account/insights',
            'search_console' => 'webmasters/v3/sites',
            'ga4' => 'analyticsadmin/v1beta/accountSummaries',
            default => 'connection/test',
        };
    }
}
