<?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 ListIntegrationsEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/integrations';
  }

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

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

    $args = [
      'page' => $request->get_param('page') ?? 1,
      'per_page' => $request->get_param('per_page') ?? 20,
      'status' => $request->get_param('status'),
      'provider' => $request->get_param('provider'),
      'category' => $request->get_param('category'),
    ];

    $result = $service->getAllIntegrations($args);

    foreach ($result['integrations'] as &$integration) {
      $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' => $result,
    ], 200);
  }
}
