<?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 Posts_Validator implements Source_Validator_Interface {

	/**
	 * Validates the parameters for post-type-based datasets.
	 *
	 * Ensures the selected post type exists in WordPress.
	 *
	 * @param  array  $config  Configuration array containing post type.
	 *
	 * @throws Exception If the post type does not exist.
	 *
	 * @since 1.0.0
	 */
	public function validate( array $config ): void {
		$post_type = $config['post_type'];
		if ( empty( get_post_type_object( $post_type ) ) ) {
			throw new Exception( Error_Codes::VALIDATION_INVALID_VALUE,
				sprintf( __( 'Invalid Post type %s', 'limb-chatbot' ), $post_type ) );
		}
	}

	/**
	 * Gets the total number of posts to be included in the dataset.
	 *
	 * @param  array  $config  Configuration array containing post type and limit.
	 *
	 * @return int Total number of posts.
	 *
	 * @throws Exception If the limit is missing or total is empty.
	 *
	 * @since 1.0.0
	 */
	public function get_total( array $config ): int {
		$post_type = $config['post_type'];
		$limit     = $config['limit'];
		if ( $limit === 'all' ) {
			$total = wp_count_posts( $post_type )->publish;
		} elseif ( is_numeric( $limit ) ) {
			$count = wp_count_posts( $post_type )->publish;
			$total = min( $limit, $count );
		} elseif ( is_array( $limit ) ) {
			$posts = get_posts( [
				'post_type'   => $post_type,
				'numberposts' => - 1,
				'fields'      => 'ids',
				'post__in'    => $limit
			] );
			$count = ! empty( $posts ) ? count( $posts ) : 0;
			$total = min( $limit, $count );
		} else {
			throw new Exception( Error_Codes::MISSING_VALUE, __( 'Limit is missing', 'limb-chatbot' ) );
		}
		if ( empty( $total ) ) {
			throw new Exception( Error_Codes::EMPTY_VALUE, __( 'Total is empty', 'limb-chatbot' ) );
		}

		return $total;
	}
}