<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

use WP_REST_Request;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Integrations\Services\ConversionAutomationService;
use PloverCRM\Modules\Integrations\Services\AutomationsLogger;
use PloverCRM\Modules\Integrations\Services\GoogleAdsConversionActionResolver;

/**
 * Save Google Mapping Endpoint
 * 
 * Handles saving stage-to-conversion mappings.
 * Auto-creates conversion actions in Google Ads if not provided.
 */
class SaveGoogleMappingEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/google/mappings';
  }

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

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

  public function handle(WP_REST_Request $request)
  {
    $params = $request->get_params();

    $connectionId = absint($params['connection_id']);
    $triggerId = sanitize_text_field($params['trigger_id']);
    $conversionActionId = sanitize_text_field($params['conversion_action_id'] ?? '');
    $conversionActionName = sanitize_text_field($params['conversion_action_name'] ?? '');

    $logger = new AutomationsLogger();

    if (empty($conversionActionId)) {
      $logger->info("Auto-creating conversion action", [
        'connection_id' => $connectionId,
        'trigger_id' => $triggerId,
        'platform' => 'google'
      ]);

      try {
        $conversionData = GoogleAdsConversionActionResolver::ensureForStage(
          $connectionId,
          $triggerId
        );
        $conversionActionId = $conversionData['id'];
        $conversionActionName = $conversionData['name'];

        $logger->info("Conversion action created/reused successfully", [
          'conversion_action_id' => $conversionActionId,
          'conversion_action_name' => $conversionActionName,
          'platform' => 'google'
        ]);
      } catch (\Exception $e) {
        $logger->error("Failed to create conversion action", [
          'connection_id' => $connectionId,
          'trigger_id' => $triggerId,
          'error' => $e->getMessage(),
          'platform' => 'google'
        ]);

        if (defined('WP_DEBUG') && WP_DEBUG) {
          error_log('[SaveGoogleMappingEndpoint] Error creating conversion: ' . $e->getMessage());
        }
        return new \WP_Error(
          'conversion_creation_failed',
          'Failed to create conversion action: ' . $e->getMessage(),
          ['status' => 500]
        );
      }
    }

    $data = [
      'connection_id' => $connectionId,
      'trigger_type' => sanitize_text_field($params['trigger_type']),
      'trigger_id' => $triggerId,
      'conversion_action_id' => $conversionActionId,
      'conversion_action_name' => $conversionActionName,
      'conversion_value' => !empty($params['conversion_value']) ? floatval($params['conversion_value']) : null,
      'currency_code' => !empty($params['currency_code']) ? sanitize_text_field($params['currency_code']) : 'USD',
    ];

    if (!empty($params['id'])) {
      $data['id'] = absint($params['id']);
    }

    try {
      $id = ConversionAutomationService::saveGoogleMapping($data);
    } catch (\Throwable $e) {
      return new \WP_Error(
        'google_mapping_save_failed',
        $e->getMessage(),
        ['status' => 400]
      );
    }

    $logger->info("Google Ads mapping saved", [
      'mapping_id' => $id,
      'connection_id' => $connectionId,
      'trigger_id' => $triggerId,
      'conversion_action_id' => $conversionActionId,
      'platform' => 'google'
    ]);

    return [
      'success' => true,
      'mapping_id' => $id,
      'conversion_action_id' => $conversionActionId,
      'conversion_action_name' => $conversionActionName
    ];
  }
}
