/*!
 * Built by ShiftSoftware
 * Copyright (c)
 */
'use strict';

function buildQueryArray(query) {
    if (!query)
        return [];
    if (typeof query === 'string') {
        const clean = query.startsWith('?') ? query.slice(1) : query;
        return clean
            .split('&')
            .filter(Boolean)
            .map(pair => pair.trim());
    }
    return Object.entries(query)
        .filter(([_, v]) => v !== undefined && v !== null)
        .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(String(v))}`);
}
function parseEndpointObject(endpoint) {
    let endpointObject;
    try {
        if (typeof endpoint === 'string')
            endpointObject = JSON.parse(endpoint);
        else
            endpointObject = endpoint;
    }
    catch (error) {
        endpointObject = { url: endpoint };
    }
    return endpointObject;
}
function fetchFrom(endpoint, props = {}) {
    let endpointObject = parseEndpointObject(endpoint);
    const defaultHeaders = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Accept-Language': (props === null || props === void 0 ? void 0 : props.language) || 'en',
    };
    const propsQueryArray = buildQueryArray(props === null || props === void 0 ? void 0 : props.query);
    const endpointQueryArray = buildQueryArray(endpointObject === null || endpointObject === void 0 ? void 0 : endpointObject.query);
    const query = [...propsQueryArray, ...endpointQueryArray].join('&');
    const queryString = query ? `?${query}` : '';
    const method = ((endpointObject === null || endpointObject === void 0 ? void 0 : endpointObject.method) || (props === null || props === void 0 ? void 0 : props.method) || 'GET');
    const config = {
        method,
        signal: props === null || props === void 0 ? void 0 : props.signal,
        headers: Object.assign(Object.assign(Object.assign({}, defaultHeaders), ((endpointObject === null || endpointObject === void 0 ? void 0 : endpointObject.headers) || {})), ((props === null || props === void 0 ? void 0 : props.headers) || {})),
    };
    if (method !== 'GET')
        config.body = JSON.stringify(Object.assign(Object.assign({}, ((props === null || props === void 0 ? void 0 : props.body) || {})), ((endpointObject === null || endpointObject === void 0 ? void 0 : endpointObject.body) || {})));
    const url = `${endpointObject.url + ((props === null || props === void 0 ? void 0 : props.additionalPath) || '')}${queryString}`;
    return fetch(url, config);
}

exports.fetchFrom = fetchFrom;
