<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

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

/**
 * Get Google Conversion Actions Endpoint
 * 
 * Fetches conversion actions for a specific Google Ads customer account.
 */
class GetGoogleConversionActionsEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/google/connections/(?P<id>\d+)/conversion-actions';
  }

  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)
  {
    $connectionId = (int) $request->get_param('id');
    
    $config = get_option('plover_crm_google_config', []);

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

    // Get connection to verify it exists
    $connection = GoogleAdsConnectionService::getConnection($connectionId);
    if (!$connection) {
      return new \WP_Error('not_found', 'Connection not found.', ['status' => 404]);
    }

    $service = new GoogleAdsService();

    try {
      $actions = $service->getConversionActions($config['developer_token'], $connection->customer_id);

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