<?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 UpdateIntegrationEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/integrations/(?P<id>\d+)';
  }

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

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

    $service = new DataSourceService($this->container);

    $existing = $service->getIntegration($id);
    if (!$existing) {
      return new WP_Error('not_found', 'Integration not found', ['status' => 404]);
    }

    // Validate required field if mappings are being updated
    if (isset($data['field_mappings'])) {
      $crm = $this->container->get('crm');
      $uniqueFieldInfo = $crm->getRequiredUniqueField();

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

      $hasRequiredField = false;
      foreach ($data['field_mappings'] 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]
        );
      }
    }

    $result = $service->updateIntegration($id, $data);

    if (!$result) {
      return new WP_Error('update_failed', 'Failed to update integration', ['status' => 500]);
    }

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

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

  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) ?: [];
  }
}
