<?php

namespace App\Services\Integrations;

use App\Models\PlatformConnection;
use App\Services\Credentials\CredentialVault;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class GoogleAdsApiService
{
    public function __construct(
        private readonly CredentialVault $vault,
        private readonly GoogleOAuthService $oauth,
    ) {}

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

        try {
            $payload = $this->vault->payload($connection->secureCredential);
            $developerToken = $payload['developer_token'] ?? config('services.google_ads.developer_token', env('GOOGLE_ADS_DEVELOPER_TOKEN'));
            $loginCustomerId = $payload['login_customer_id'] ?? null;
            $version = config('services.google_ads.version', env('GOOGLE_ADS_API_VERSION', 'v23'));

            if (blank($developerToken)) {
                return IntegrationTestResult::failed('Google Ads developer token eksik.');
            }

            $accessToken = $this->oauth->accessTokenFromRefreshToken($connection);
            $headers = [
                'Authorization' => 'Bearer '.$accessToken,
                'developer-token' => $developerToken,
            ];

            if (filled($loginCustomerId)) {
                $headers['login-customer-id'] = preg_replace('/\D+/', '', $loginCustomerId);
            }

            $endpoint = "https://googleads.googleapis.com/{$version}/customers:listAccessibleCustomers";
            $response = Http::withHeaders($headers)->timeout(45)->get($endpoint);
            $duration = (int) round((microtime(true) - $started) * 1000);

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

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

            return IntegrationTestResult::success('Google Ads bağlantısı başarılı. Erişilebilir hesap sayısı: '.count($resourceNames), [
                'resource_names' => array_slice($resourceNames, 0, 10),
                'total_accessible_customers' => count($resourceNames),
            ], $response->status(), $duration);
        } catch (\Throwable $e) {
            $duration = (int) round((microtime(true) - $started) * 1000);
            return IntegrationTestResult::failed($e->getMessage(), [], null, $duration);
        }
    }

    private function shortBody(string $body): string
    {
        return Str::limit($body, 700);
    }
}
