import { API_URL } from '../constants/constants.js';

export const constructUrl = (path, params, host = API_URL) => {
    if (!/^\//g.test(path)) {
        throw new Error(
            `Invalid path! Expecting a valid relative path (path needs to start with /)(${path})`,
        );
    }

    let url = path;

    if (host) {
        url = `${host}${url}`;
    }

    if (params) {
        url = `${url}?${params}`;
    }

    return url;
};

/**
 * Formats data for a POST request.
 *
 * @param {Object} body - data to be passed to the POST endpoint
 * @param {Boolean} isTraditional - similar to jQuery's option `traditional` for $.ajax(),
 *                  this serializes data in a way that helps support legacy endpoints
 */
export const formatPostData = (body) => {
    const postData = new FormData();
    Object.keys(body).forEach((key) => postData.append(key, body[key]));
    return postData;
};

const parseQueryParamsString = (queryParams) => {
    if (typeof queryParams !== 'string') {
        return null;
    }

    return queryParams;
};

const parseQueryParamsObject = (queryParams) => {
    if (queryParams === null || typeof queryParams !== 'object' || Array.isArray(queryParams)) {
        return null;
    }

    return Object.keys(queryParams)
        .map((key) => {
            const value = queryParams[key];
            return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        })
        .join('&');
};

const parseQueryParamsArray = (queryParams) => {
    if (!Array.isArray(queryParams)) {
        return null;
    }

    return queryParams
        .map((param) => {
            const [key, value] = param.split('=');
            return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
        })
        .join('&');
};

export const parseQueryParams = (queryParams) =>
    parseQueryParamsString(queryParams) ||
    parseQueryParamsObject(queryParams) ||
    parseQueryParamsArray(queryParams) ||
    '';

export const request = (url, options) => {
    try {
        return fetch(url, options).catch((err) => console.error(err));
    } catch (error) {
        return Promise.reject(error);
    }
};

export const unwrapJson = (response) => response.json();

export const validateResponse = (response) => response;
