<?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;

/**
 * Get Sources Endpoint
 * 
 * Returns available sources (forms, products, etc.) from a provider
 */
class GetSourcesEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/integrations/sources/(?P<provider>[a-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');
    $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]
      );
    }

    $sources = $provider->getSources();

    return new WP_REST_Response([
      'success' => true,
      'data' => [
        'provider' => [
          'key' => $provider->getKey(),
          'name' => $provider->getName(),
          'icon' => $provider->getIcon(),
          'category' => $provider->getCategory(),
        ],
        'sources' => $sources,
        'events' => $provider->getSupportedEvents(),
      ],
    ], 200);
  }
}
