<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

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

/**
 * Get Source Fields Endpoint
 * 
 * Returns fields from a specific source and CRM fields for mapping
 * CRM-agnostic: works with any CRM provider
 */
class GetSourceFieldsEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/integrations/source-fields/(?P<provider>[a-z0-9_]+)/(?P<source_id>[a-zA-Z0-9_-]+)';
  }

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

  public function handle(WP_REST_Request $request): WP_REST_Response|WP_Error
  {
    $providerKey = $request->get_param('provider');
    $sourceId = $request->get_param('source_id');

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

    if (!$provider) {
      return new WP_Error(
        'invalid_provider',
        'Provider not found or not available',
        ['status' => 404]
      );
    }

    // Get source fields
    $sourceFields = $provider->getSourceFields($sourceId);

    // Get CRM fields from active CRM provider
    $crm = $this->container->get('crm');
    if ($providerKey === 'meta_lead_ads') {
      $provisioner = new SystemFieldProvisioner($this->container);
      $provisioner->ensureCapabilityIfActive(SystemFieldRegistry::CAPABILITY_META_LEAD_ADS, $crm);
    }

    $mappingPayload = CrmFieldMappingBuilder::build($crm);

    return new WP_REST_Response([
      'success' => true,
      'data' => [
        'source_fields' => $sourceFields,
        'crm_fields' => $mappingPayload['crmFields'],
        'required_field' => [
          'key' => $mappingPayload['requiredUniqueField']['key'],
          'label' => $mappingPayload['requiredUniqueField']['label'],
          'is_custom_field' => $mappingPayload['requiredUniqueField']['isCustomField'],
        ],
      ],
    ], 200);
  }
}
