<?php

namespace App\Services\Integrations\Sdk;

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

class GoogleAdsSdkClientFactory
{
    public function __construct(private readonly CredentialVault $vault) {}

    public function installed(): bool
    {
        return (bool) $this->sdkVersionNamespace();
    }

    public function versionNamespace(): ?string
    {
        return $this->sdkVersionNamespace();
    }

    /**
     * @return object
     */
    public function make(PlatformConnection $connection): object
    {
        $version = $this->sdkVersionNamespace();
        if (! $version) {
            throw new \RuntimeException('googleads/google-ads-php kurulu değil. composer require googleads/google-ads-php çalıştırılmalı.');
        }

        $payload = $this->vault->payload($connection->secureCredential);
        $developerToken = $payload['developer_token'] ?? config('services.google_ads.developer_token', env('GOOGLE_ADS_DEVELOPER_TOKEN'));
        $clientId = $payload['google_client_id'] ?? $payload['client_id'] ?? config('services.google.client_id', env('GOOGLE_CLIENT_ID'));
        $clientSecret = $payload['google_client_secret'] ?? $payload['client_secret'] ?? config('services.google.client_secret', env('GOOGLE_CLIENT_SECRET'));
        $refreshToken = $payload['refresh_token'] ?? null;
        $loginCustomerId = preg_replace('/\D+/', '', (string) ($payload['login_customer_id'] ?? ''));

        foreach (compact('developerToken', 'clientId', 'clientSecret', 'refreshToken') as $key => $value) {
            if (blank($value)) {
                throw new \RuntimeException('Google Ads SDK için '.$key.' eksik.');
            }
        }

        $oauthBuilder = "Google\\Ads\\GoogleAds\\Lib\\{$version}\\OAuth2TokenBuilder";
        $clientBuilder = "Google\\Ads\\GoogleAds\\Lib\\{$version}\\GoogleAdsClientBuilder";

        $oAuth2Credential = (new $oauthBuilder())
            ->withClientId($clientId)
            ->withClientSecret($clientSecret)
            ->withRefreshToken($refreshToken)
            ->build();

        $builder = (new $clientBuilder())
            ->withDeveloperToken($developerToken)
            ->withOAuth2Credential($oAuth2Credential);

        if (filled($loginCustomerId)) {
            $builder = $builder->withLoginCustomerId((int) $loginCustomerId);
        }

        return $builder->build();
    }

    private function sdkVersionNamespace(): ?string
    {
        foreach (['V24', 'V23', 'V22', 'V21', 'V20', 'V19'] as $version) {
            if (class_exists("Google\\Ads\\GoogleAds\\Lib\\{$version}\\GoogleAdsClientBuilder")) {
                return $version;
            }
        }

        return null;
    }
}
