<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

use WP_REST_Request;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Integrations\Services\GoogleAdsService;

/**
 * Get Google Ads Accounts Endpoint
 * 
 * Fetches accessible Google Ads customer accounts.
 */
class GetGoogleAccountsEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/google/accounts';
  }

  public function getMethod()
  {
    return 'GET';
  }

  public function checkPermission(WP_REST_Request $request)
  {
    return $this->checkAuthenticatedCapability($request, 'manage_options');
  }

  public function handle(WP_REST_Request $request)
  {
    $config = get_option('plover_crm_google_config', []);

    if (empty($config['refresh_token'])) {
      return new \WP_Error('not_authenticated', 'Please connect your Google account first.', ['status' => 401]);
    }

    if (empty($config['developer_token'])) {
      return new \WP_Error('missing_dev_token', 'Developer token not configured.', ['status' => 400]);
    }

    $service = new GoogleAdsService();

    try {
      $customers = $service->listAccessibleCustomers($config['developer_token']);

      return $this->success([
        'customers' => $customers,
      ]);
    } catch (\Exception $e) {
      return new \WP_Error('api_error', $e->getMessage(), ['status' => 500]);
    }
  }
}
