<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Source_Validators;

use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Interfaces\Source_Validator_Interface;

class CPT_Validator implements Source_Validator_Interface {

	public function validate( array $config ): void {
		// Validate the CPT
		$cpt_name = $config['post_type'] ?? null;
		if ( ! $cpt_name || ! post_type_exists( $cpt_name ) ) {
			throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE, __( 'The selected custom post type is invalid. Please verify your selection.', 'limb-chatbot' ) );
		}
		// Validate the taxonomies
		$taxonomies = $config['taxonomies'] ?? null;
		if ( ! empty( $taxnomies ) && is_array( $taxonomies ) ) {
			foreach ( $taxnomies as $taxonomy ) {
				if ( ! taxonomy_exists( $taxonomy ) ) {
					throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE, __( 'One or more selected taxonomies are invalid. Please verify your taxonomy selection.', 'limb-chatbot' ) );
				}
				if ( ! is_object_in_taxonomy( $cpt_name, $taxonomy ) ) {
					throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE, __( 'The selected custom post type does not support one or more of the selected taxonomies. Please verify your selection.', 'limb-chatbot' ) );
				}
			}
		}
		// Validate limits
		$limit = $config['limit'] ?? null;
		if ( empty( $limit ) ) {
			throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE, __( 'The limit is required.', 'limb-chatbot' ) );
		}
		if ( is_array( $limit ) ) {
			foreach ( $limit as $post_id ) {
				if ( ! get_post( $post_id ) instanceof \WP_Post ) {
					throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE, __( 'One or more selected posts are invalid.', 'limb-chatbot' ) );
				}
			}
		}
		if ( is_int( $limit ) && $limit <= 0 ) {
			throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE, __( 'The limit must be a positive integer.', 'limb-chatbot' ) );
		}
	}

	public function get_total( array $config ): int {
		$limit    = $config['limit'] ?? null;
		$cpt_name = $config['post_type'] ?? null;
		if ( is_int( $limit ) ) {
			$count = wp_count_posts( $limit )->publish;

			return min( $limit, $count );
		}
		if ( is_array( $limit ) ) {
			$posts = get_posts( [
				'post_type'   => $cpt_name,
				'numberposts' => - 1,
				'fields'      => 'ids',
				'post__in'    => $limit
			] );
			$count = ! empty( $posts ) ? count( $posts ) : 0;

			return min( $limit, $count );
		}
		if ( $limit === 'all' ) {
			return wp_count_posts( $cpt_name )->publish;
		}

		throw new Exception( Error_Codes::EMPTY_VALUE, __( 'Total is empty', 'limb-chatbot' ) );
	}
}

