<?php

declare(strict_types=1);

if (!defined('ABSPATH')) {
  exit;
}

/**
 * Handles all connection-related functionality including testing and validation
 */
class KLCNN_API_Connection extends KLCNN_API_Base
{
  /**
   * WordPress REST API callback for testing connection
   */
  public static function test_connection_endpoint($request)
  {
    $params = $request->get_json_params();

    if (empty($params['clientKey']) || empty($params['secretKey'])) {
      return new WP_Error(
        'missing_credentials',
        'Client Key and Secret Key are required',
        ['status' => 400]
      );
    }

    try {
      $client_key = sanitize_text_field($params['clientKey']);
      $secret_key = sanitize_text_field($params['secretKey']);

      $api = new self($client_key, $secret_key);

      // First validate credential format
      $api->validate_credentials($client_key, $secret_key);

      // Then test the actual connection
      $result = $api->test_connection();

      return rest_ensure_response([
        'success' => true,
        'message' => 'Connection successful',
        'data' => $result['data'] ?? []
      ]);
    } catch (Exception $e) {
      $status = $e->getCode() ?: 400;
      return new WP_Error(
        'connection_failed',
        $e->getMessage(),
        ['status' => $status]
      );
    }
  }

  private function test_connection(): array
  {
    // First validate the credentials format
    $this->validate_credentials($this->client_key, $this->secret_key);

    // Remove any whitespace from keys
    $this->client_key = trim($this->client_key);
    $this->secret_key = trim($this->secret_key);
    // Make the exact same request as shown in documentation
    return $this->request('GET', 'categories', []);
  }

  /**
   * Save valid connection credentials
   */
  public function save_credentials(string $client_key, string $secret_key): bool
  {
    // First validate and test the connection
    $this->validate_credentials($client_key, $secret_key);
    $this->test_connection();

    // Encrypt sensitive data before storing
    $encryption = KLCNN_Encryption::get_instance();
    $encrypted_client_key = $encryption->encrypt($client_key);
    $encrypted_secret_key = $encryption->encrypt($secret_key);

    // If we get here, the credentials are valid, so save them
    update_option('klcnn_client_key', $encrypted_client_key);
    update_option('klcnn_secret_key', $encrypted_secret_key);

    return true;
  }

  /**
   * Get saved credentials
   */
  public static function get_credentials(): array
  {
    $encryption = KLCNN_Encryption::get_instance();
    $encrypted_client_key = get_option('klcnn_client_key', '');
    $encrypted_secret_key = get_option('klcnn_secret_key', '');

    return [
      'client_key' => $encrypted_client_key ? $encryption->decrypt($encrypted_client_key) : '',
      'secret_key' => $encrypted_secret_key ? $encryption->decrypt($encrypted_secret_key) : ''
    ];
  }
  public function validate_connection()
  {
    $result = $this->test_connection();

    if (!$result['success']) {
      return $result;
    }

    // Add additional validation if needed
    return [
      'success' => true,
      'message' => 'Connection successful',
      'account' => $result['data']
    ];
  }

  /**
   * WordPress REST API callback for getting connection status
   */
  public static function get_connection_endpoint($request)
  {
    try {
      $credentials = self::get_credentials();

      if (empty($credentials['client_key']) || empty($credentials['secret_key'])) {
        return rest_ensure_response([
          'success' => false,
          'message' => 'No connection found'
        ]);
      }

      return rest_ensure_response([
        'success' => true,
        'data' => [
          'clientId' => $credentials['client_key'],
          'connectedSince' => get_option('klcnn_connected_since', ''),
          'marketplace' => get_option('klcnn_marketplace', 'de')
        ]
      ]);
    } catch (Exception $e) {
      return new WP_Error(
        'get_connection_failed',
        $e->getMessage(),
        ['status' => 400]
      );
    }
  }

  /**
   * WordPress REST API callback for saving connection
   */
  public static function save_connection_endpoint($request)
  {
    $params = $request->get_json_params();

    if (empty($params['clientId']) || empty($params['clientSecret'])) {
      return new WP_Error(
        'missing_credentials',
        'Client ID and Client Secret are required',
        ['status' => 400]
      );
    }

    try {
      $api = new self($params['clientId'], $params['clientSecret']);

      // First validate credential format
      $api->validate_credentials($params['clientId'], $params['clientSecret']);

      // Then test the connection
      $api->test_connection();

      // If we get here, save the credentials
      update_option('klcnn_client_key', $params['clientId']);
      update_option('klcnn_secret_key', $params['clientSecret']);
      update_option('klcnn_marketplace', $params['marketplace'] ?? 'de');
      update_option('klcnn_connected_since', current_time('mysql'));

      return rest_ensure_response([
        'success' => true,
        'message' => 'Connection saved successfully',
        'data' => [
          'clientId' => $params['clientId'],
          'connectedSince' => current_time('mysql'),
          'marketplace' => $params['marketplace'] ?? 'de'
        ]
      ]);
    } catch (Exception $e) {
      return new WP_Error(
        'save_connection_failed',
        $e->getMessage(),
        ['status' => 400]
      );
    }
  }

  /**
   * WordPress REST API callback for deleting connection
   */
  public static function delete_connection_endpoint($request)
  {
    try {
      delete_option('klcnn_client_key');
      delete_option('klcnn_secret_key');
      delete_option('klcnn_marketplace');
      delete_option('klcnn_connected_since');

      return rest_ensure_response([
        'success' => true,
        'message' => 'Connection deleted successfully'
      ]);
    } catch (Exception $e) {
      return new WP_Error(
        'delete_connection_failed',
        $e->getMessage(),
        ['status' => 400]
      );
    }
  }

  /**
   * WordPress REST API callback for getting secret key
   */
  public static function get_secret_key_endpoint($request)
  {
    try {
      $credentials = self::get_credentials();

      if (empty($credentials['secret_key'])) {
        return new WP_Error(
          'no_secret_key',
          'No secret key found',
          ['status' => 404]
        );
      }

      return rest_ensure_response([
        'success' => true,
        'secretKey' => $credentials['secret_key']
      ]);
    } catch (Exception $e) {
      return new WP_Error(
        'get_secret_failed',
        $e->getMessage(),
        ['status' => 400]
      );
    }
  }
}
