<?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 SaveGoogleConnectionEndpoint extends AbstractEndpoint
{
  public function getRoute(): string
  {
    return '/google/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)
  {
    $customerId = sanitize_text_field($request->get_param('customer_id'));
    $customerName = sanitize_text_field($request->get_param('customer_name'));

    if (empty($customerId)) {
      return new \WP_Error('missing_params', 'Customer ID is required', ['status' => 400]);
    }

    $config = get_option('plover_crm_google_config', []);

    if (empty($config['refresh_token'])) {
      return new \WP_Error('no_auth', 'No authorized Google account found.', ['status' => 400]);
    }

    GoogleAdsConnectionService::ensureTableExists();

    $id = GoogleAdsConnectionService::addConnection([
      'customer_id' => $customerId,
      'customer_name' => $customerName ?: 'Account ' . $customerId,
    ]);

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

    $connection = GoogleAdsConnectionService::getConnection($id);
    (new AutomationsLogger())->logConnection(
      'connected',
      'google',
      $customerId,
      $customerName ?: 'Account ' . $customerId
    );

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