import {urlSearchParams} from "../../../helpers";
import {handleResponse} from "../../helpers/rest";

/**
 * Get AI models
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {object} params Query params
 * @return {Promise<any>}
 * @constructor
 */
export const GetModels = (restUrl, restNonce, params = {}) => {
    const query = urlSearchParams(params);

    return fetch(`${restUrl}ai_models${query}`, {
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        }
    }).then(handleResponse);
}

/**
 * Get model
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {number} id Model id
 * @param {object} params Query params
 * @return {Promise<*>}
 * @constructor
 */
export const GetModel = (restUrl, restNonce, id, params = {}) => {
    const query = urlSearchParams(params);

    return fetch(`${restUrl}ai_models/${id}${query}`, {
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        }
    }).then(handleResponse);
}

/**
 * Get model by name
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {string} name Model name
 * @param {object} params Additional query params
 * @return {Promise<any>}
 * @constructor
 */
export const GetModelByName = async (restUrl, restNonce, name, params = {}) => {
    const queryParams = {
        ...params,
        name: name
    };
    const result = await GetModels(restUrl, restNonce, queryParams);
    // Return the first item from the results, or null if no results
    return result?.items?.length > 0 ? result.items[0] : null;
}

/**
 * Delete model
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {number} id Model id
 * @constructor
 */
export const DeleteModel = (restUrl, restNonce, id) => {
    return fetch(`${restUrl}ai_models/${id}`, {
        method: 'DELETE',
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        }
    }).then(handleResponse);
}