<?php

namespace PloverCRM\Modules\Integrations\Services;

use Exception;
use WP_Error;

/**
 * Google Token Service
 * 
 * Handles token refresh via the PloverCRM backend API (Managed Mode only).
 */
class GoogleTokenService
{
    const PLOVER_BACKEND_REFRESH_URL = 'https://webplover.com/api/google/refresh';

    /**
     * Get a valid access token, auto-refreshing if necessary.
     *
     * @return string
     * @throws Exception
     */
    public function getValidAccessToken(): string
    {
        $config = get_option('plover_crm_google_config', []);

        if (empty($config['refresh_token'])) {
            throw new Exception('Google Ads not connected. Please connect your account.');
        }

        if ($this->isTokenExpired($config)) {
            return $this->refreshToken($config);
        }

        return $config['access_token'] ?? '';
    }

    /**
     * Check if token is expired (older than 50 minutes to be safe).
     */
    private function isTokenExpired(array $config): bool
    {
        if (empty($config['access_token']) || empty($config['updated_at'])) {
            return true;
        }

        $age = time() - (int)$config['updated_at'];
        // Refresh if older than 50 minutes (3000 seconds)
        return $age > 3000;
    }

    /**
     * Refresh token via the PloverCRM backend API.
     */
    private function refreshToken(array $config): string
    {
        if (empty($config['refresh_token'])) {
            throw new Exception('No refresh token available. Please reconnect Google Ads.');
        }

        $response = wp_remote_post(self::PLOVER_BACKEND_REFRESH_URL, [
            'body' => json_encode(['refresh_token' => $config['refresh_token']]),
            'headers' => ['Content-Type' => 'application/json'],
            'timeout' => 15
        ]);

        if (is_wp_error($response)) {
            throw new Exception('Failed to contact authentication server.');
        }

        $responseCode = wp_remote_retrieve_response_code($response);
        $responseBody = wp_remote_retrieve_body($response);
        $body = json_decode($responseBody, true);

        if ($responseCode !== 200 || empty($body['success']) || empty($body['access_token'])) {
            throw new Exception('Automatic refresh failed. Please reconnect Google Ads.');
        }

        // Save new token
        $config['access_token'] = sanitize_text_field($body['access_token']);
        $config['updated_at'] = time();
        update_option('plover_crm_google_config', $config);

        return $config['access_token'];
    }
}
