<?php

namespace Limb_Chatbot\Includes\Api\V1\Controllers;

use Exception;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception as LBAIC_Exception;
use Limb_Chatbot\Includes\Repositories\Dataset_Group_Repository;
use Limb_Chatbot\Includes\Services\Dataset_Group_Service;
use Limb_Chatbot\Includes\Services\Helper;
use WP_REST_Server;

class Dataset_Groups_Controller extends Rest_Controller {

	protected $rest_base = 'datasets/groups';

	protected Dataset_Group_Repository $repository;
	protected Dataset_Group_Service $service;

	public function __construct() {
		$this->repository = new Dataset_Group_Repository();
		$this->service    = new Dataset_Group_Service( $this->repository );
	}

	public function register_routes(): void {
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'permission_callback' => array( $this, 'permission_callback' ),
					'callback'            => array( $this, 'get_items' ),
				),
			)
		);
		register_rest_route( $this->namespace, '/' . $this->rest_base, array(
				array(
					'methods'             => WP_REST_Server::EDITABLE,
					'permission_callback' => array( $this, 'permission_callback' ),
					'callback'            => array( $this, 'update_item' ),
					'args'                => $this->get_update_args(),
				),
			)
		);
	}

	private function get_update_args(): array {
		return [
			'slug'             => [
				'required'          => true,
				'type'              => 'array',
				'sanitize_callback' => static function ( $value ) {
					if ( ! is_array( $value ) ) {
						return [];
					}

					return array_values(
						array_filter(
							array_map(
								static function ( $slug ) {
									return is_string( $slug ) ? trim( sanitize_text_field( $slug ) ) : '';
								},
								$value
							),
							static function ( $slug ) {
								return '' !== $slug;
							}
						)
					);
				},
				'validate_callback' => static function ( $value ) {
					if ( ! is_array( $value ) || empty( $value ) ) {
						return false;
					}

					foreach ( $value as $slug ) {
						if ( ! is_string( $slug ) || '' === trim( $slug ) ) {
							return false;
						}
					}

					return true;
				},
			],
			'status'           => [
				'validate_callback' => static function ( $value ) {
					return in_array( (int) $value, [ 0, 1 ], true );
				},
			],
			'content_config'   => [
				'type'              => 'object',
				'validate_callback' => static function ( $value ) {
					return is_array( $value );
				},
			],
			'user_roles'       => [
				'type'              => 'array',
				'validate_callback' => static function ( $value ) {
					return is_array( $value );
				},
			],
			'autosync_enabled' => [
				'validate_callback' => static function ( $value ) {
					return in_array( (int) $value, [ 0, 1 ], true );
				},
			],
		];
	}

	public function permission_callback( $request ): bool {
		if ( ! parent::permission_callback( $request ) ) {
			return false;
		}

		return current_user_can( 'manage_options' );
	}

	public function get_items( $request ) {
		try {
			$collection = $this->repository->get_groups( $request->get_query_params() );
			$collection = $this->set_pagination_params( $collection, $request );

			return rest_ensure_response( $collection );
		} catch ( Exception $e ) {
			Helper::log( $e, __METHOD__ );

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

	public function update_item( $request ) {
		try {
			$payload = $request->get_json_params();

			return rest_ensure_response( $this->service->update_groups( $payload ) );
		} catch ( Exception $e ) {
			Helper::log( $e, __METHOD__ );

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