<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Source_Object_Fetchers;

use Limb_Chatbot\Includes\Interfaces\Source_Fetcher_Interface;

/**
 * Class Terms_Source_Fetcher
 *
 * Fetches dataset entries from WordPress taxonomy terms
 * 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 Terms_Source_Fetcher implements Source_Fetcher_Interface {

	/**
	 * Fetch dataset entries from WordPress taxonomy terms.
	 *
	 * Retrieves term 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 {
		$taxonomy       = $config['taxonomy'];
		$limit          = $config['limit'];
		$args = [
			'taxonomy' => $taxonomy,
			'number'   => $item['per_page'],
			'offset'   => ( $item['paged'] - 1 ) * $item['per_page'],
			'fields'   => 'ids',
			'orderby'  => 'name',
			'order'    => 'ASC'
		];

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

		$ids = get_terms( $args );

		$result = [];
		foreach ( $ids as $id ) {
			$result[] = [
				'source'          => $id,
				'source_type'     => 'term',
				'source_sub_type' => $taxonomy,
			];
		}

		return $result;
	}
}
