<?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;

/**
 * Update a webhook endpoint
 */
class UpdateWebhookEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/webhooks/(?P<id>\d+)';
  }

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

  public function handle(WP_REST_Request $request): WP_REST_Response|WP_Error
  {
    $id = (int) $request->get_param('id');
    $data = $request->get_json_params();

    $existing = WebhookService::getById($id);
    if (!$existing) {
      return new WP_Error('not_found', 'Webhook not found', ['status' => 404]);
    }

    $updated = WebhookService::update($id, $data);

    if (!$updated) {
      return new WP_Error('update_failed', 'Failed to update webhook', ['status' => 500]);
    }

    $webhook = WebhookService::getById($id);
    $webhook['url'] = WebhookService::getWebhookUrl($webhook['token']);

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