/*!
 * Crafted with ❤ by Salla
 */
const DEBUG_KEY = 'salla-delivery-promise-debug';
function log(message, data) {
    if (localStorage.getItem(DEBUG_KEY)) {
        data !== undefined ? console.log(message, data) : console.log(message);
    }
}
/** Fetch available cities for a product's delivery promises. */
export async function fetchCities(productId) {
    log('fetchCities start', { productId });
    const response = await salla.api.request(salla.url.api(`products/${productId}/delivery-promises/cities`));
    if (!response.success || !Array.isArray(response.data) || response.data.length === 0) {
        log('fetchCities: no data', { response });
        return { cities: [], preselected: undefined };
    }
    const preselected = response.data.find((c) => c.is_selected);
    log('fetchCities success', { count: response.data.length, preselected });
    return { cities: response.data, preselected };
}
/** Fetch the delivery promise message for a given city or branch. */
export async function fetchDeliveryMessage(productId, id, optionType, isLoginCycleEnabled) {
    log('fetchDeliveryMessage start', { productId, id, optionType });
    let queryString = '';
    if (optionType === 'city' && !isLoginCycleEnabled) {
        queryString = `?reference_id=${id}`;
    }
    else {
        queryString = `?reference_id=${id}&reference_type=${optionType}`;
    }
    const response = (await salla.api.withoutNotifier(() => salla.api.request(salla.url.api(`products/${productId}/delivery-promises${queryString}`))));
    if (!response.success) {
        log('fetchDeliveryMessage error', { response });
        throw new Error(response.error?.message || 'Failed to fetch delivery promise');
    }
    const message = response.data?.message?.trim();
    log('fetchDeliveryMessage success', { message });
    return message || null;
}
