<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

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

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

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

  public function handle(WP_REST_Request $request)
  {
    $providerKey = sanitize_text_field((string) $request->get_param('provider'));
    $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');
    }

    return $this->success([
      'provider' => [
        'key' => $provider->getKey(),
        'name' => $provider->getName(),
        'iconUrl' => $service->getIconUrl($provider->getIcon()),
        'category' => $provider->getCategory(),
      ],
      'sources' => array_map([DataSourceApiSerializer::class, 'source'], $provider->getSources()),
      'events' => array_map([DataSourceApiSerializer::class, 'event'], $provider->getSupportedEvents()),
    ]);
  }
}
