<?php

namespace Limb_Chatbot\Includes\Api\V1\Controllers;

use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Data_Objects\Chat;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Repositories\Chat_Meta_Repository;
use Limb_Chatbot\Includes\Services\Helper;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

/**
 * REST API controller for managing chat metas.
 *
 * Handles retrieval and batch updates of chat meta entries.
 *
 * @since 1.0.0
 */
class Chat_Metas_Controller extends Rest_Controller {

	/**
	 * REST base route with chat ID parameter.
	 *
	 * @var string
	 * @since 1.0.0
	 */
	protected $rest_base = 'chats/(?P<chat_uuid>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})/metas';

	/**
	 * Repository instance for chat metas.
	 *
	 * @var Chat_Meta_Repository
	 * @since 1.0.0
	 */
	protected Chat_Meta_Repository $repository;

	/**
	 * Constructor.
	 *
	 * Initializes the chat meta repository.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$this->repository = new Chat_Meta_Repository();
	}

	/**
	 * Registers REST API routes for chat metas.
	 *
	 * @since 1.0.0
	 */
	public function register_routes(): void {
		register_rest_route( $this->namespace, '/' . $this->rest_base . '/batch', array(
			array(
				'methods'             => WP_REST_Server::CREATABLE,
				'callback'            => array( $this, 'batch_update_items' ),
				'permission_callback' => array( $this, 'permission_callback' ),
				'args'                => $this->get_chat_uuid_arg(),
			),
			array(
				'methods'             => WP_REST_Server::EDITABLE,
				'callback'            => array( $this, 'batch_update_items' ),
				'permission_callback' => array( $this, 'permission_callback' ),
				'args'                => $this->get_chat_uuid_arg(),
			)
		) );
	}

	/**
	 * Returns the argument definition for validating chat_uuid parameter.
	 *
	 * @return array Argument definition.
	 * @since 1.0.0
	 */
	private function get_chat_uuid_arg(): array {
		return array(
			'chat_uuid' => array(
				'type'              => 'string',
				'validate_callback' => function ( $value, $request, $param ) {
					return ! empty( Chat::count( [ 'uuid' => $value ] ) );
				}
			)
		);
	}

	/**
	 * Performs batch update of chat metas.
	 *
	 * Validates batch data and updates metas for the given chat ID.
	 *
	 * @param  WP_REST_Request  $request  Incoming REST request.
	 *
	 * @return WP_REST_Response|WP_Error REST response or error.
	 * @since 1.0.0
	 */
	public function batch_update_items( $request ) {
		try {
			$items = $request->get_json_params();
			if ( ! is_array( $items ) ) {
				throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE,
					__( 'Invalid data format: expected an array of items.', 'limb-chatbot' ) );
			}
			unset( $items['_current_tab'], $items['_from_admin'] );
			$error = $this->validate_batch_items( $items, $this->get_item_schema()['properties'] );
			if ( is_wp_error( $error ) ) {
				return $error;
			}

			return rest_ensure_response( $this->repository->batch_update( $items, $request->get_param( 'chat_uuid' ) ) );
		} catch ( \Exception $e ) {
			Helper::log( $e, __METHOD__ );

			return Helper::get_wp_error( $e );
		}
	}

	/**
	 * Returns JSON schema for chat meta resource.
	 *
	 * Defines structure and validation for chat meta.
	 *
	 * @return array JSON schema array.
	 * @since 1.0.0
	 */
	public function get_item_schema(): array {
		if ( $this->schema ) {
			// Since WordPress 5.3, the schema can be cached in the $schema property.
			return $this->schema;
		}
		$this->schema = array(
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
			'title'      => 'Chat Meta',
			'type'       => 'object',
			'properties' => array(
				'id'         => array(
					'description'       => __( 'Unique identifier for the resource.', 'limb-chatbot' ),
					'type'              => 'integer',
					'context'           => array( 'view', 'edit' ),
					'readonly'          => true,
					'sanitize_callback' => 'absint',
				),
				'chat_uuid'    => array(
					'description' => __( 'The chat uuid.', 'limb-chatbot' ),
					'type'        => 'string',
					'context'     => array( 'view', 'edit' ),
					'arg_options' => array(
						'validate_callback' => $this->get_chat_uuid_arg()['chat_uuid']['validate_callback'],
					)
				),
				'meta_key'   => array(
					'description'       => __( 'Key of the resource', 'limb-chatbot' ),
					'type'              => 'string',
					'required'          => true,
					'sanitize_callback' => 'sanitize_text_field',
				),
				'meta_value' => array(
					'description' => __( 'Value of the resource', 'limb-chatbot' ),
					'type'        => array( 'string', 'integer', 'array' ),
					'required'    => true
				)
			),
		);

		return $this->schema;
	}
}
