<?php

namespace PloverCRM\Modules\Integrations\Services;

use PloverCRM\Core\Container;

/**
 * Provides metadata needed by the standalone Data Sources app UI.
 */
class DataSourcesAppBootstrapService
{
  public static function build(Container $container): array
  {
    $service = new DataSourceService($container);
    $crm = $container->get('crm');
    $categories = $service->getCategories();
    $integrationsResult = $service->getAllIntegrations([
      'page' => 1,
      'per_page' => 500,
    ]);
    $webhooks = WebhookService::getAll();
    $defaultCategoryKey = 'forms';

    $serializedCategories = array_map(function ($category) use ($service) {
      return DataSourceApiSerializer::category(
        $category,
        $service->getAllProvidersByCategory((string) ($category['key'] ?? ''))
      );
    }, $categories);

    foreach ($serializedCategories as $category) {
      if (!empty($category['hasProviders'])) {
        $defaultCategoryKey = $category['key'];
        break;
      }
    }

    return [
      'defaultCategoryKey' => $defaultCategoryKey,
      'crm' => [
        'name' => $crm->getName(),
        'lists' => array_map([DataSourceApiSerializer::class, 'crmItem'], $crm->getAllLists()),
        'tags' => array_map([DataSourceApiSerializer::class, 'crmItem'], $crm->getAllTags()),
        'requiredUniqueField' => self::serializeRequiredUniqueField($crm->getRequiredUniqueField()),
      ],
      'categories' => $serializedCategories,
      'integrations' => array_map(function ($integration) use ($service) {
        return DataSourceApiSerializer::integration($integration, $service);
      }, $integrationsResult['integrations']),
      'webhooks' => array_map(function ($webhook) {
        $webhook['url'] = WebhookService::getWebhookUrl((string) ($webhook['token'] ?? ''));
        $webhook['has_payload'] = !empty($webhook['last_payload']);
        return DataSourceApiSerializer::webhook($webhook);
      }, $webhooks),
    ];
  }

  private static function serializeRequiredUniqueField(array $field): array
  {
    return [
      'key' => !empty($field['is_custom_field'])
        ? 'cf_' . (string) ($field['field'] ?? '')
        : (string) ($field['field'] ?? ''),
      'label' => (string) ($field['label'] ?? ''),
      'isCustomField' => !empty($field['is_custom_field']),
    ];
  }
}
