<?php

namespace Limb_Chatbot\Includes\Services\Knowledge\Source_Object_Fetchers;

use Limb_Chatbot\Includes\Data_Objects\Dataset;
use Limb_Chatbot\Includes\Data_Objects\File;
use Limb_Chatbot\Includes\Exceptions\Error_Codes;
use Limb_Chatbot\Includes\Exceptions\Exception;
use Limb_Chatbot\Includes\Interfaces\Source_Fetcher_Interface;

/**
 * File source fetcher implementation.
 *
 * Fetches dataset source objects based on file UUIDs stored in settings.
 *
 * @package Limb_Chatbot\Includes\Services\Knowledge\Source_Object_Fetchers
 * @since 1.0.0
 */
class File_Source_Fetcher implements Source_Fetcher_Interface {

	/**
	 * Fetches dataset source objects for the given pagination parameters.
	 *
	 * @param  array  $item    Pagination parameters including 'paged' and 'per_page'.
	 * @param  array  $config  Job configuration containing 'files' array of UUIDs.
	 *
	 * @return array Array of dataset source objects.
	 * @throws Exception If a file UUID cannot be resolved.
	 *
	 * @since 1.0.0
	 */
	public function fetch( array $item, array $config ): array {
		$file_uuids = $config['files'];
		$offset     = ( $item['paged'] - 1 ) * $item['per_page'];
		$file_uuids = array_slice( $file_uuids, $offset, $item['per_page'] );
		$result     = [];
		foreach ( $file_uuids as $id ) {
			$file = File::find_by_uuid( $id );
			if ( ! $file instanceof File ) {
				throw new Exception(
					Error_Codes::VALIDATION_INVALID_VALUE,
					sprintf(
						/* translators: %s: file UUID */
						__( 'File with UUID "%s" not found during task generation.', 'limb-chatbot' ),
						esc_html( (string) $id )
					)
				);
			}
			$result[] = [
				'source'          => $id,
				'source_type'     => Dataset::SOURCE_FILE,
				'source_sub_type' => $file->get_mime_type(),
			];
		}

		return $result;
	}
}