<?php

namespace App\Services\Integrations\Sdk;

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

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

    public function installed(): bool
    {
        return class_exists('Google\\Client');
    }

    /**
     * @return object
     */
    public function make(PlatformConnection $connection, array $scopes = []): object
    {
        if (! $this->installed()) {
            throw new \RuntimeException('google/apiclient kurulu değil. composer require google/apiclient çalıştırılmalı.');
        }

        $payload = $this->vault->payload($connection->secureCredential);
        $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;

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

        $clientClass = 'Google\\Client';
        $client = new $clientClass();
        $client->setClientId($clientId);
        $client->setClientSecret($clientSecret);
        $client->setAccessType('offline');

        foreach ($scopes as $scope) {
            $client->addScope($scope);
        }

        $client->fetchAccessTokenWithRefreshToken($refreshToken);

        return $client;
    }
}
