<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Integrations\Services\DataSourceService;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;

class CreateIntegrationEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/integrations';
  }

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

  public function handle(WP_REST_Request $request): WP_REST_Response|WP_Error
  {
    $data = $request->get_json_params();

    if (empty($data['name'])) {
      return new WP_Error('missing_name', 'Integration name is required', ['status' => 400]);
    }

    if (empty($data['provider'])) {
      return new WP_Error('missing_provider', 'Provider is required', ['status' => 400]);
    }

    if (empty($data['source_id'])) {
      return new WP_Error('missing_source_id', 'Source ID is required', ['status' => 400]);
    }

    $service = new DataSourceService($this->container);
    $provider = $service->getProvider($data['provider']);

    if (!$provider) {
      return new WP_Error('invalid_provider', 'Invalid provider', ['status' => 400]);
    }

    // Validate required field mapping using active CRM
    $fieldMappings = $data['field_mappings'] ?? [];
    $crm = $this->container->get('crm');
    $uniqueFieldInfo = $crm->getRequiredUniqueField();

    $requiredField = $uniqueFieldInfo['is_custom_field']
      ? 'cf_' . $uniqueFieldInfo['field']
      : $uniqueFieldInfo['field'];

    $hasRequiredField = false;
    foreach ($fieldMappings as $mapping) {
      if (
        ($mapping['crm_field'] ?? $mapping['crmField'] ?? '') === $requiredField
        && !empty($mapping['source_field'] ?? $mapping['sourceField'] ?? '')
      ) {
        $hasRequiredField = true;
        break;
      }
    }

    if (!$hasRequiredField) {
      return new WP_Error(
        'missing_required_field',
        sprintf('The required field "%s" must be mapped', $uniqueFieldInfo['label']),
        ['status' => 400]
      );
    }

    $id = $service->createIntegration($data);

    if (!$id) {
      return new WP_Error('create_failed', 'Failed to create integration', ['status' => 500]);
    }

    $integration = $service->getIntegration($id);
    $this->decodeJsonFields($integration);

    return new WP_REST_Response([
      'success' => true,
      'message' => 'Integration created successfully',
      'data' => $integration,
    ], 201);
  }

  private function decodeJsonFields(&$integration): void
  {
    $integration->field_mappings = json_decode($integration->field_mappings, true) ?: [];
    $integration->lists = json_decode($integration->lists, true) ?: [];
    $integration->tags = json_decode($integration->tags, true) ?: [];
    $integration->options = json_decode($integration->options, true) ?: [];
    $integration->conditions = json_decode($integration->conditions, true) ?: [];
  }
}
