<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

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

class DeleteGoogleConnectionEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/google/connections/(?P<id>\d+)';
  }

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

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

  public function handle(WP_REST_Request $request)
  {
    $id = (int) $request->get_param('id');
    $connection = GoogleAdsConnectionService::getConnection($id);
    if (GoogleAdsConnectionService::deleteConnection($id)) {
      (new AutomationsLogger())->logConnection(
        'disconnected',
        'google',
        (string) ($connection->customer_id ?? $id),
        (string) ($connection->customer_name ?? 'Google Ads account')
      );
      return $this->success([
        'deleted' => true,
        'connectionId' => $id,
      ]);
    }
    return new \WP_Error('delete_failed', 'Failed to delete connection.', ['status' => 500]);
  }
}
