<?php

namespace App\Services\Platforms\Auth;

use App\Contracts\PlatformTokenRefresher;
use App\Models\PlatformConnection;
use Illuminate\Support\Facades\Http;
use RuntimeException;

class GoogleTokenRefresher implements PlatformTokenRefresher
{
    public function refresh(PlatformConnection $connection): PlatformConnection
    {
        $refreshToken = (string) $connection->refresh_token;

        if (blank($refreshToken)) {
            $error = 'Google connection cannot be refreshed: refresh_token is missing.';
            $connection->update(['last_error' => $error]);

            throw new RuntimeException($error);
        }

        $clientId = $connection->platform_data['client_id']
            ?? (config('services.google_ads.oauth_client_id') ?: config('services.google_ads.client_id'));
        $clientSecret = $connection->platform_data['client_secret']
            ?? (config('services.google_ads.oauth_client_secret') ?: config('services.google_ads.client_secret'));

        $response = Http::asForm()
            ->connectTimeout(5)
            ->timeout(10)
            ->post('https://oauth2.googleapis.com/token', [
                'client_id' => $clientId,
                'client_secret' => $clientSecret,
                'refresh_token' => $refreshToken,
                'grant_type' => 'refresh_token',
            ]);

        if ($response->failed() || ! is_string($response->json('access_token'))) {
            $error = sprintf('Google OAuth token refresh failed: %s', $response->body());
            $connection->update(['last_error' => $error]);

            throw new RuntimeException($error);
        }

        $expiresIn = (int) $response->json('expires_in', 3600);

        $connection->update([
            'access_token' => (string) $response->json('access_token'),
            'expires_at' => now()->addSeconds($expiresIn),
            'last_refreshed_at' => now(),
            'last_error' => null,
        ]);

        return $connection->fresh();
    }
}
