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

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

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

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

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

    $deleted = WebhookService::delete($id);

    if (!$deleted) {
      return new WP_Error('delete_failed', 'Failed to delete webhook', ['status' => 500]);
    }

    return new WP_REST_Response([
      'success' => true,
      'message' => 'Webhook deleted',
    ], 200);
  }
}
