<?php

namespace PloverCRM\Modules\Integrations\Providers;

use PloverCRM\Modules\Integrations\Services\WebhookService;

/**
 * Webhook Provider
 * 
 * Incoming webhook data source.
 * Provides webhook endpoints as "sources" that external systems can POST data to.
 * Field discovery happens automatically from the last received payload.
 */
class WebhookProvider implements DataSourceProviderInterface
{
  private $eventCallback;

  public function getKey(): string
  {
    return 'webhook';
  }

  public function getName(): string
  {
    return 'Incoming Webhook';
  }

  public function getIcon(): string
  {
    return 'webhooks.svg';
  }

  public function getCategory(): string
  {
    return 'webhooks';
  }

  public function isAvailable(): bool
  {
    return true;
  }

  public function getSupportedEvents(): array
  {
    return [
      ['key' => 'data_received', 'label' => 'Data Received'],
    ];
  }

  /**
   * Get available webhook endpoints as sources
   */
  public function getSources(): array
  {
    $webhooks = WebhookService::getAll();

    return array_map(fn($webhook) => [
      'id' => (string) $webhook['id'],
      'title' => $webhook['name'],
      'url' => WebhookService::getWebhookUrl($webhook['token']),
      'status' => $webhook['status'],
      'has_payload' => !empty($webhook['last_payload']),
    ], $webhooks);
  }

  /**
   * Get discovered fields from the last received payload
   */
  public function getSourceFields(string $sourceId): array
  {
    return WebhookService::getDiscoveredFields((int) $sourceId);
  }

  /**
   * Register event listener — called by DataSourceService
   * The actual triggering happens in IncomingWebhookEndpoint
   */
  public function registerEventListener(callable $callback): void
  {
    $this->eventCallback = $callback;

    // Store callback globally so IncomingWebhookEndpoint can access it
    add_filter('plover_crm/webhook_event_callback', function () {
      return $this->eventCallback;
    });
  }
}
