<?php
/**
 * Playground
 *
 * @class Playground
 * @package KimaAI\Ai
 * @since 1.1.0
 */

declare(strict_types=1);

namespace KimaAI\Ai;

use KimaAI\Admin\Settings;
use KimaAI\Models\ImageModel;
use WP_REST_Request;
use WP_REST_Response;
use Exception;

defined('ABSPATH') || exit;

/**
 * Class Playground
 */
class Playground {
  /**
   * Create the playground REST controller.
   */
  public function __construct(
    public Settings $settings,
    public ImageModel $image_model,
    public AiService $ai_service
  ) {
  }

  /**
   * Registers REST API routes.
   * Allowed actions: 'chat', 'image', 'text-to-speech', 'assistants', 'list',
   */
  public function registerRoutes(): void {
    register_rest_route(
      'kimaai/v1',
      '/playground/(?P<action>[a-zA-Z0-9-_]+)',
      [
        'methods' => 'POST',
        'callback' => [$this, 'request'],
        'permission_callback' => fn() => current_user_can('manage_options'),
      ]
    );

    register_rest_route(
      'kimaai/v1',
      '/playground/image-history',
      [
        'methods' => 'GET',
        'callback' => [$this, 'imageHistory'],
        'permission_callback' => fn() => current_user_can('manage_options'),
      ]
    );

    register_rest_route(
      'kimaai/v1',
      '/playground/image-history/delete',
      [
        'methods' => 'POST',
        'callback' => [$this, 'deleteImageHistory'],
        'permission_callback' => fn() => current_user_can('manage_options'),
        'args' => [
          'id' => [
            'required' => true,
            'validate_callback' => fn($param) => is_numeric($param) && $param > 0,
          ],
        ],
      ]
    );
  }

  /**
   * Handles the Playground request.
   *
   * @param WP_REST_Request $request The REST request object.
   *
   * @return WP_REST_Response The REST response object.
   */
  public function request(WP_REST_Request $request): WP_REST_Response {
    // Allow long generations without PHP killing the request.
    // phpcs:ignore
    @ignore_user_abort(true);
    // phpcs:ignore
    @set_time_limit(120);

    $action = $request->get_param('action');
    $data = $request->get_json_params();

    if (empty($action) || empty($data)) {
      return new WP_REST_Response([
        'error' => __('Action and data are required.', 'kimaai'),
      ], 400);
    }

    try {
      $result = $this->ai_service->run($data, $action, true);
      return new WP_REST_Response($result, 200);
    } catch (Exception $exception) {
      return new WP_REST_Response([
        'error' => $exception->getMessage(),
      ], 500);
    }
  }

  /**
   * Retrieves all image history.
   *
   * @return WP_REST_Response The REST response object.
   */
  public function imageHistory(): WP_REST_Response {
    $image_history = $this->image_model->all();
    return new WP_REST_Response($image_history, 200);
  }

  /**
   * Deletes an image history entry.
   *
   * @param WP_REST_Request $request The REST request object.
   * @return WP_REST_Response The REST response object.
   */
  public function deleteImageHistory(WP_REST_Request $request): WP_REST_Response {
    $id = (int) $request->get_param('id');

    if ($this->image_model->delete($id)) {
      return new WP_REST_Response(['message' => 'Image history entry deleted successfully.'], 200);
    }
    else {
      return new WP_REST_Response(['error' => 'Failed to delete image history entry.'], 500);
    }
  }
}
