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

/**
 * Get Leads table columns for mapping (e.g. lead capture fields).
 * API returns {items: [{id, field_key, label, data_type}], total, page, per_page}.
 *
 * @param {object} params Query parameters (page, per_page, search, etc.)
 * @return {Promise<{items: Array, total: number, page: number, per_page: number}>}
 */
export const GetLeadsColumns = (params = {}) => {
    const query = urlSearchParams(params);

    return fetch(`${LimbChatbot.rest.url}lead-fields${query}`, {
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        }
    }).then(handleResponse);
};

/**
 * Create a new lead field.
 * API expects {data_type: string, label: string}.
 * Returns {id: number, field_key: string, label: string, data_type: string}.
 *
 * @param {object} data Field data {data_type, label}
 * @return {Promise<{id: number, field_key: string, label: string, data_type: string}>}
 */
export const CreateLeadColumn = (data) => {
    return fetch(`${LimbChatbot.rest.url}lead-fields`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        },
        body: JSON.stringify(data)
    }).then(handleResponse);
};

/**
 * Get Leads data.
 * API returns {items: Array, total: number, page: number, per_page: number}.
 *
 * @param {object} params Query parameters (page, per_page, search, etc.)
 * @return {Promise<{items: Array, total: number, page: number, per_page: number}>}
 */
export const GetLeads = (params = {}) => {
    const query = urlSearchParams(params);

    return fetch(`${LimbChatbot.rest.url}leads${query}`, {
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': LimbChatbot.rest.nonce
        }
    }).then(handleResponse);
};
