<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

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

/**
 * Delete Integration Endpoint
 */
class DeleteIntegrationEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/integrations/(?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');
    $service = new DataSourceService($this->container);

    // Check if integration exists
    $existing = $service->getIntegration($id);
    if (!$existing) {
      return new WP_Error('not_found', 'Integration not found', ['status' => 404]);
    }

    $result = $service->deleteIntegration($id);

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

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