<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Integrations\Services\DataSourceApiSerializer;
use PloverCRM\Modules\Integrations\Services\CrmFieldMappingBuilder;
use PloverCRM\Modules\Integrations\Services\DataSourceService;
use WP_REST_Request;

class DataSourceFieldsEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/data-sources/providers/(?P<provider>[a-z0-9_]+)/sources/(?P<source_id>[a-zA-Z0-9_-]+)/fields';
  }

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

  public function handle(WP_REST_Request $request)
  {
    $providerKey = sanitize_text_field((string) $request->get_param('provider'));
    $sourceId = sanitize_text_field((string) $request->get_param('source_id'));
    $service = new DataSourceService($this->container);
    $provider = $service->getProvider($providerKey);

    if (!$provider) {
      return $this->error('Provider not found or not available.', 404, 'data_source_provider_not_found');
    }

    $crm = $this->container->get('crm');
    $sourceFields = $provider->getSourceFields($sourceId);
    $mappingPayload = CrmFieldMappingBuilder::build($crm);

    return $this->success([
      'sourceFields' => array_map([DataSourceApiSerializer::class, 'sourceField'], $sourceFields),
      'crmFields' => array_map([DataSourceApiSerializer::class, 'crmField'], $mappingPayload['crmFields']),
      'requiredUniqueField' => $mappingPayload['requiredUniqueField'],
    ]);
  }
}
