<?php
/**
 * RestApi class for KimaAI AI modules.
 *
 * @class RestApi
 * @package KimaAI\Ai
 * @since 1.2.5
 */

declare(strict_types=1);

namespace KimaAI\Ai;

use KimaAI\Logger;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

class RestApi {

  /**
   * Create the AI REST API controller.
   */
  public function __construct(public AiService $ai_service) {
  }

  /**
   * Register REST API routes.
   *
   * @hook rest_api_init
   */
  public function registerRoutes(): void {
    // Example route for AI models
    register_rest_route('kimaai/v1', '/test-connection', [
      'methods' => 'POST',
      'callback' => [$this, 'testConnection'],
      'permission_callback' => fn() => current_user_can('manage_options'),
    ]);
  }

  /**
   * Test connection to the AI service.
   *
   * @param WP_REST_Request $request The REST request object.
   * @return WP_REST_Response
   */
  public function testConnection(WP_REST_Request $request): WP_REST_Response {
    $params = $request->get_params();
    $provider = $params['provider'] ?? null;
    $api_key = $params['apiKey'] ?? null;
    $endpoint = isset($params['endpoint']) ? trim((string) $params['endpoint']) : '';

    if (!$provider || (!$api_key && $provider !== 'ollama')) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Provider and API key are required.',
      ], 400);
    }

    try {
      $options = [];
      if ($endpoint !== '') {
        $options['baseUrl'] = $endpoint;
      }

      $is_working = $this->ai_service->testConnection($provider, $api_key, $options);
      if ($is_working) {
        $message = __('Connection was successful.', 'kimaai');
        Logger::info($message);
        return new WP_REST_Response([
          'success' => true,
          'message' => $message,
        ], 200);
      }
      else {
        $message = __('Connection failed. Please check your API key and provider settings.', 'kimaai');
        Logger::warn($message);
        return new WP_REST_Response([
          'success' => false,
          'message' => $message,
        ], 400);
      }
    } catch (\Exception $exception) {
      Logger::error('Error testing AI connection: ' . $exception->getMessage());
      return new WP_REST_Response([
        'success' => false,
        'message' => $exception->getMessage(),
      ], 500);
    }
  }
}
