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

/**
 * Create a new webhook endpoint
 */
class CreateWebhookEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/webhooks';
  }

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

  public function handle(WP_REST_Request $request): WP_REST_Response|WP_Error
  {
    $data = $request->get_json_params();
    $name = $data['name'] ?? '';

    if (empty($name)) {
      return new WP_Error('missing_name', 'Webhook name is required', ['status' => 400]);
    }

    $webhook = WebhookService::create($name);

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

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

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