<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

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

/**
 * Save Meta CAPI Mapping Endpoint.
 */
class SaveMetaCapiMappingEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/meta-capi/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();

    $data = [
      'connection_id' => absint($params['connection_id'] ?? 0),
      'trigger_type' => sanitize_text_field($params['trigger_type'] ?? 'stage_changed'),
      'trigger_id' => sanitize_text_field($params['trigger_id'] ?? ''),
      'event_name' => sanitize_text_field($params['event_name'] ?? ''),
    ];

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

    // Handle custom event name
    if (!empty($params['custom_event_name'])) {
      $data['custom_event_name'] = sanitize_text_field($params['custom_event_name']);
    }

    // Handle custom_data (simple key-value format)
    if (isset($params['custom_data']) && is_array($params['custom_data'])) {
      $data['custom_data'] = $params['custom_data'];
    }

    // Handle structured custom data parameters.
    if (isset($params['custom_data_parameters']) && is_array($params['custom_data_parameters'])) {
      $sanitizedParams = [];
      foreach ($params['custom_data_parameters'] as $param) {
        if (isset($param['type']) && isset($param['value'])) {
          $sanitizedParams[] = [
            'type' => sanitize_text_field($param['type']),
            'value' => sanitize_text_field($param['value']),
          ];
        }
      }
      $data['custom_data_parameters'] = $sanitizedParams;
    }

    // Validate
    if (empty($data['connection_id']) || empty($data['trigger_id']) || empty($data['event_name'])) {
      return new \WP_Error(
        'missing_fields',
        'Connection, Stage, and Event Name are required',
        ['status' => 400]
      );
    }

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

    return [
      'success' => true,
      'mapping_id' => $id
    ];
  }
}
