<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

use WP_REST_Request;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Integrations\Services\AutomationsLogger;
use PloverCRM\Modules\Integrations\Services\MetaCapiConnectionService;

/**
 * Delete Meta CAPI Connection Endpoint
 */
class DeleteMetaCapiConnectionEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/meta-capi/connections/(?P<id>\d+)';
  }

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

  public function checkPermission(WP_REST_Request $request)
  {
    return $this->checkAuthenticatedCapability($request, 'manage_options');
  }

  public function getRouteParams(): array
  {
    return [
      'id' => [
        'type' => 'integer',
        'required' => true,
      ]
    ];
  }

  public function handle(WP_REST_Request $request)
  {
    $id = absint($request->get_param('id'));
    $connection = MetaCapiConnectionService::getConnection($id);

    $result = MetaCapiConnectionService::deleteConnection($id);

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

    (new AutomationsLogger())->logConnection(
      'disconnected',
      'meta',
      (string) ($connection->dataset_id ?? $id),
      (string) ($connection->name ?? 'Meta dataset')
    );

    return $this->success([
      'deleted' => true,
      'connectionId' => $id,
    ]);
  }
}
