/**
 * Internal dependencies.
 */
import http from '@spectra-pro-helpers/http';
import { formatParams } from '@spectra-pro-helpers/index';

/**
 * API class for handling HTTP requests to a specified URI.
 * It leverages a pre-configured HTTP client and a parameter formatting utility to simplify
 * API interactions.
 */
class API {
	/**
	 * The base URI for the REST API endpoint (with trailing slash).
	 *
	 * @type {string}
	 */
	uri;

	/**
	 * Constructs an API instance with a base URI.
	 *
	 * @param {string} uri - The base URI of the REST API endpoint (e.g., 'wp/v2/posts').
	 */
	constructor( uri ) {
		this.uri = `${ uri }/`;
	}

	/**
	 * Retrieves a list of resources from the endpoint with optional query parameters.
	 *
	 * @param {Object} [query] - Optional query parameters to filter the list.
	 * @return {Promise<Object>} A promise resolving to the API response data.
	 * @example
	 * api.list({ per_page: 5, order: 'asc' }) // Fetches 5 items in ascending order.
	 */
	async list( query ) {
		return http( {
			path: query ? `${ this.uri }?${ formatParams( query ) }` : this.uri,
			method: 'get',
		} ).then( ( res ) => res );
	}
}

export default API;
