<?php

declare(strict_types=1);

namespace PloverCRM\Modules\Integrations\Endpoints;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Integrations\Services\WebhookService;

/**
 * List all webhook endpoints
 */
class ListWebhooksEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/webhooks';
  }

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

  public function handle(WP_REST_Request $request): WP_REST_Response|WP_Error
  {
    $webhooks = WebhookService::getAll();

    // Add URL to each webhook
    foreach ($webhooks as &$webhook) {
      $webhook['url'] = WebhookService::getWebhookUrl($webhook['token']);
      $webhook['has_payload'] = !empty($webhook['last_payload']);
      unset($webhook['last_payload']); // Don't send full payload in list
    }

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