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

/**
 * Save Meta CAPI Connection Endpoint
 */
class SaveMetaCapiConnectionEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/meta-capi/connections';
  }

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

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

  public function handle(WP_REST_Request $request)
  {
    $params = $request->get_params();
    $logger = new AutomationsLogger();

    $data = [
      'name' => sanitize_text_field($params['name'] ?? ''),
      'dataset_id' => sanitize_text_field($params['dataset_id'] ?? ''),
      'access_token' => sanitize_text_field($params['access_token'] ?? ''),
    ];

    // Validate
    if (empty($data['name']) || empty($data['dataset_id']) || empty($data['access_token'])) {
      return new \WP_Error(
        'missing_fields',
        'Name, Dataset ID, and Access Token are required',
        ['status' => 400]
      );
    }

    // Test connection first
    $testResult = MetaCapiConnectionService::testConnection($data['dataset_id'], $data['access_token']);
    if (!$testResult['success']) {
      $logger->error('Meta connection validation failed', [
        'dataset_id' => $data['dataset_id'],
        'connection_name' => $data['name'],
        'error' => (string) ($testResult['message'] ?? 'Validation failed'),
        '_activity' => [
          'module' => 'integrations',
          'feature' => 'connections',
        ],
      ]);

      return new \WP_Error(
        'connection_failed',
        'Failed to validate credentials: ' . $testResult['message'],
        ['status' => 400]
      );
    }

    // Add connection
    $id = MetaCapiConnectionService::addConnection($data);

    if (!$id) {
      return new \WP_Error(
        'save_failed',
        'Failed to save connection. Dataset ID may already be connected.',
        ['status' => 500]
      );
    }

    $connection = MetaCapiConnectionService::getConnection($id);
    $logger->logConnection(
      'connected',
      'meta',
      $data['dataset_id'],
      $data['name']
    );

    return $this->success([
      'connection' => $connection->toPublicArray(),
    ], [], 201);
  }
}
