<?php

namespace App\Services\Keywords;

use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V25\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V25\GoogleAdsClientBuilder;
use InvalidArgumentException;

class GoogleAdsClientFactory
{
    /**
     * @return list<string>
     */
    public function missingConfigurationKeys(): array
    {
        $missing = [];

        foreach ([
            'developer_token' => 'GOOGLE_ADS_DEVELOPER_TOKEN',
            'client_id' => 'GOOGLE_ADS_CLIENT_ID',
            'client_secret' => 'GOOGLE_ADS_CLIENT_SECRET',
            'refresh_token' => 'GOOGLE_ADS_REFRESH_TOKEN',
        ] as $configKey => $envKey) {
            if (! filled(config("google-ads.{$configKey}"))) {
                $missing[] = $envKey;
            }
        }

        return $missing;
    }

    public function make(): GoogleAdsClient
    {
        $missing = $this->missingConfigurationKeys();

        if ($missing !== []) {
            throw new InvalidArgumentException(
                'Missing Google Ads configuration: '.implode(', ', $missing),
            );
        }

        $oAuth2Credential = (new OAuth2TokenBuilder)
            ->withClientId((string) config('google-ads.client_id'))
            ->withClientSecret((string) config('google-ads.client_secret'))
            ->withRefreshToken((string) config('google-ads.refresh_token'))
            ->build();

        $builder = (new GoogleAdsClientBuilder)
            ->withDeveloperToken((string) config('google-ads.developer_token'))
            ->withOAuth2Credential($oAuth2Credential);

        $loginCustomerId = $this->normalizeCustomerId(config('google-ads.login_customer_id'));

        if ($loginCustomerId !== null) {
            $builder->withLoginCustomerId($loginCustomerId);
        }

        return $builder->build();
    }

    public function resolveCustomerId(): ?string
    {
        $configuredCustomerId = $this->normalizeCustomerId(config('google-ads.customer_id'));

        if ($configuredCustomerId !== null) {
            return (string) $configuredCustomerId;
        }

        $loginCustomerId = $this->normalizeCustomerId(config('google-ads.login_customer_id'));

        return $loginCustomerId !== null ? (string) $loginCustomerId : null;
    }

    public function normalizeCustomerId(mixed $customerId): ?int
    {
        if (! filled($customerId)) {
            return null;
        }

        $digits = preg_replace('/\D+/', '', (string) $customerId);

        if ($digits === null || $digits === '') {
            return null;
        }

        return (int) $digits;
    }
}
