<?php

namespace Limb_Chatbot\Includes\Api\V1\Controllers;

use Exception;
use Limb_Chatbot\Includes\Data_Objects\Dataset;
use Limb_Chatbot\Includes\Data_Objects\Dataset_Meta;
use Limb_Chatbot\Includes\Repositories\Dataset_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 dataset metas.
 *
 * Handles retrieval and batch updates of dataset meta entries.
 *
 * @since 1.0.0
 */
class Dataset_Metas_Controller extends Rest_Controller {

	/**
	 * REST base route with dataset ID parameter.
	 *
	 * @var string
	 * @since 1.0.0
	 */
	protected $rest_base = 'datasets/(?P<dataset_id>[\d]+)/metas';

	/**
	 * Repository instance for dataset metas.
	 *
	 * @var Dataset_Meta_Repository
	 * @since 1.0.0
	 */
	protected Dataset_Meta_Repository $repository;

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

	/**
	 * Registers REST API routes for dataset metas.
	 *
	 * @since 1.0.0
	 */
	public function register_routes(): void {
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'get_items' ),
				'permission_callback' => array( $this, 'permission_callback' ),
				'args'                => array_merge( $this->get_dataset_id_arg(), $this->get_collection_params() ),
			),
		) );
		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_dataset_id_arg(),
			),
			array(
				'methods'             => WP_REST_Server::EDITABLE,
				'callback'            => array( $this, 'batch_update_items' ),
				'permission_callback' => array( $this, 'permission_callback' ),
				'args'                => $this->get_dataset_id_arg(),
			)
		) );
	}

	/**
	 * Returns the argument definition for validating dataset_id parameter.
	 *
	 * @return array Argument definition.
	 * @since 1.0.0
	 */
	private function get_dataset_id_arg(): array {
		return array(
			'dataset_id' => array(
				'type'              => 'integer',
				'validate_callback' => function ( $value, $request, $param ) {
					return ! empty( Dataset::count( [ 'id' => $value ] ) );
				}
			)
		);
	}

	/**
	 * Returns the argument definition for validating meta_key parameter.
	 *
	 * @return array Argument definition.
	 * @since 1.0.0
	 */
	private function get_meta_key_arg(): array {
		return array(
			'meta_key' => array(
				'type'     => 'string',
				'required' => true,
			)
		);
	}

	/**
	 * Retrieves dataset meta items based on query parameters.
	 *
	 * @param  WP_REST_Request  $request  Incoming REST request.
	 *
	 * @return WP_REST_Response|WP_Error REST response or error.
	 * @since 1.0.0
	 */
	public function get_items( $request ) {
		try {
			return rest_ensure_response( Dataset_Meta::where( $request->get_query_params() + [ 'dataset_id' => $request->get_param( 'dataset_id' ) ] )->get() );
		} catch ( Exception $e ) {
			Helper::log( $e, __METHOD__ );

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

	/**
	 * Performs batch update of dataset metas.
	 *
	 * Validates batch data and updates metas for the given dataset 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();
			$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( 'dataset_id' ) ) );
		} catch ( Exception $e ) {
			Helper::log( $e, __METHOD__ );

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

	/**
	 * Returns collection query parameters including meta_key.
	 *
	 * @return array Collection query parameters.
	 * @since 1.0.0
	 */
	public function get_collection_params() {
		$parent = parent::get_collection_params();

		return array_merge( $parent, array(
			'meta_key' => array(
				'description'       => __( 'Key of the resource', 'limb-chatbot' ),
				'type'              => array( 'string', 'array' ),
				'required'          => true,
				'sanitize_callback' => function ( $value ) {
					if ( is_string( $value ) ) {
						return sanitize_text_field( $value );
					} else {
						return array_map( function ( $item ) {
							return sanitize_text_field( $item );
						}, $value );
					}
				},
				'validate_callback' => function ( $value, $argument, $request ) {
					return is_string( $value ) || is_array( $value );
				}
			),
		) );
	}

	/**
	 * Returns JSON schema for dataset meta resource.
	 *
	 * Defines structure and validation for dataset 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'      => 'Dataset 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',
				),
				'dataset_id' => array(
					'description' => __( 'The dataset id.', 'limb-chatbot' ),
					'type'        => 'integer',
					'context'     => array( 'view', 'edit' ),
					'arg_options' => array(
						'validate_callback' => $this->get_dataset_id_arg()['dataset_id']['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;
	}
}