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

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

  public function handle(WP_REST_Request $request): WP_REST_Response|WP_Error
  {
    $id = (int) $request->get_param('id');
    $service = new DataSourceService($this->container);

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

    if (!$integration) {
      return new WP_Error('not_found', 'Integration not found', ['status' => 404]);
    }

    $provider = $service->getProvider($integration->provider);
    if ($provider) {
      $integration->provider_name = $provider->getName();
      $integration->provider_icon = $provider->getIcon();

      $sources = $provider->getSources();
      $integration->source_name = 'Unknown';
      foreach ($sources as $source) {
        if ($source['id'] === $integration->source_id) {
          $integration->source_name = $source['title'];
          break;
        }
      }
    }

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

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