<?php
/**
 * Chatbot admin routes and handlers.
 *
 * @package KimaAI\ChatBot
 */

declare(strict_types=1);

namespace KimaAI\ChatBot;

use KimaAI\KimaAI;
use KimaAI\Models\ChatModel;
use WP_REST_Request;
use WP_REST_Response;

defined('ABSPATH') || exit;

class ChatbotAdmin {

  /**
   * Create the admin handler.
   *
   * @param ChatModel $chat_model Chat data model.
   * @param ChatbotSessionRetention $session_retention Session retention handler.
   */
  public function __construct(
    private ChatModel $chat_model,
    private ChatbotSessionRetention $session_retention
  ) {
  }

  /**
   * Register WordPress action and filter hooks.
   *
   * @return void
   */
  public function registerHooks(): void {
  }

  /**
   * Register admin REST API routes.
   *
   * @return void
   */
  public function registerRoutes(): void {
    register_rest_route(KimaAI::PREFIX . '/' . KimaAI::API_VERSION, '/chatbot/all', [
      'methods' => 'GET',
      'callback' => [$this, 'getAllChatHistories'],
      'permission_callback' => fn() => current_user_can('manage_options'),
      'args' => [
        'isPlayground' => [
          'required' => false,
          'type' => 'boolean',
          'default' => false,
        ],
      ],
    ]);
    register_rest_route(KimaAI::PREFIX . '/' . KimaAI::API_VERSION, '/chatbot/delete', [
      'methods' => 'POST',
      'callback' => [$this, 'deleteChatHistory'],
      'permission_callback' => fn() => current_user_can('manage_options'),
      'args' => [
        'id' => [
          'required' => true,
          'type' => 'integer',
        ],
      ],
    ]);
    register_rest_route(KimaAI::PREFIX . '/' . KimaAI::API_VERSION, '/chatbot/sessions', [
      'methods' => 'GET',
      'callback' => [$this, 'getChatSessions'],
      'permission_callback' => fn() => current_user_can('manage_options'),
      'args' => [
        'isPlayground' => [
          'required' => false,
          'type' => 'boolean',
          'default' => false,
        ],
      ],
    ]);
    register_rest_route(KimaAI::PREFIX . '/' . KimaAI::API_VERSION, '/chatbot/session/(?P<session_id>[^/]+)', [
      'methods' => 'GET',
      'callback' => [$this, 'getChatSessionHistory'],
      'permission_callback' => fn() => current_user_can('manage_options'),
      'args' => [
        'session_id' => [
          'required' => true,
          'type' => 'string',
        ],
      ],
    ]);
    register_rest_route(KimaAI::PREFIX . '/' . KimaAI::API_VERSION, '/chatbot/session/delete', [
      'methods' => 'POST',
      'callback' => [$this, 'deleteChatSession'],
      'permission_callback' => fn() => current_user_can('manage_options'),
      'args' => [
        'session_ids' => [
          'required' => false,
          'type' => 'array',
          'items' => ['type' => 'string'],
          'default' => [],
        ],
      ],
    ]);
  }

  /**
   * Retrieves all chat histories.
   */
  public function getAllChatHistories(WP_REST_Request $request): WP_REST_Response {
    $is_playground = $request->get_param('isPlayground');
    $histories = $this->chat_model->getAll($is_playground);
    return new WP_REST_Response($histories, 200);
  }

  /**
   * Deletes a chat history by session ID.
   */
  public function deleteChatHistory(WP_REST_Request $request): WP_REST_Response {
    $id = $request->get_param('id');
    $result = $this->chat_model->delete($id);
    return new WP_REST_Response($result, 200);
  }

  /**
   * Retrieves one summary row per chat session.
   */
  public function getChatSessions(WP_REST_Request $request): WP_REST_Response {
    $is_playground = (bool) $request->get_param('isPlayground');
    $sessions = $this->chat_model->getAllSessions($is_playground);
    return new WP_REST_Response($sessions, 200);
  }

  /**
   * Retrieves the full chat history for one session.
   */
  public function getChatSessionHistory(WP_REST_Request $request): WP_REST_Response {
    $session_id = sanitize_text_field(rawurldecode((string) $request->get_param('session_id')));
    $history = $this->chat_model->getSessionHistory($session_id);
    return new WP_REST_Response($history, 200);
  }

  /**
   * Deletes all chat rows for one or more session IDs.
   */
  public function deleteChatSession(WP_REST_Request $request): WP_REST_Response {
    $session_ids = $this->sanitizeSessionIds($request->get_param('session_ids'));

    if (empty($session_ids)) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Missing session_id or session_ids.',
      ], 400);
    }

    $existing_chat_count = $this->chat_model->countSessions($session_ids);

    try {
      $counts = $this->session_retention->deleteSessionsBatch($session_ids);

      return new WP_REST_Response([
        'success' => true,
        'session_ids' => $session_ids,
        'deleted_count' => $existing_chat_count > 0 ? (int) ($counts['chatRowsDeleted'] ?? 0) : 0,
      ], 200);
    }
    catch (\Throwable $exception) {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Failed to delete sessions.',
      ], 500);
    }
  }

  /**
   * Sanitize and deduplicate an array of session ID strings.
   *
   * @param mixed $value Raw input value.
   * @return string[]
   */
  private function sanitizeSessionIds(mixed $value): array {
    if (!is_array($value)) {
      return [];
    }

    $session_ids = array_map(
      static fn($session_id) => sanitize_text_field((string) $session_id),
      $value
    );

    $session_ids = array_filter($session_ids, static fn($session_id) => $session_id !== '');

    return array_values(array_unique($session_ids));
  }
}
