<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Source_Object_Fetchers;

use Limb_Chatbot\Includes\Interfaces\Source_Fetcher_Interface;


/**
 * Class Posts_Source_Fetcher
 *
 * Fetches dataset entries from WordPress posts based on
 * plugin configuration and pagination parameters.
 *
 * Implements the Source_Fetcher_Interface contract to provide
 * a consistent data structure for dataset generation.
 *
 * @package Limb_Chatbot\Includes\Services\Knowledge\Source_Object_Fetchers
 * @since 1.0.0
 */
class Posts_Source_Fetcher implements Source_Fetcher_Interface {

	/**
	 * Fetch dataset entries from WordPress posts.
	 *
	 * Retrieves post IDs according to plugin settings and
	 * request-specific pagination parameters, then maps them into
	 * structured dataset entries.
	 *
	 * @param  array  $item  Arguments that control fetching behavior.
	 *
	 * @return array[] Structured dataset entries.
	 * @since 1.0.0
	 */
	public function fetch( array $item, array $config ): array {
		$post_type   = $config['post_type'];
		$limit       = $config['limit'];

		$args = [
			'post_type'      => $post_type,
			'paged'          => $item['paged'],
			'posts_per_page' => $item['per_page'],
			'fields'         => 'ids',
			'orderby'        => 'date',
			'order'          => 'DESC'
		];

		if ( is_array( $limit ) ) {
			$args['post__in'] = $limit;
		}

		$ids    = get_posts( $args );
		$result = [];
		foreach ( $ids as $id ) {
			$result[] = [
				'source_type'     => 'post',
				'source'          => $id,
				'source_sub_type' => $post_type,
			];
		}

		return $result;
	}
}
