import { correlationId } from '../base/environment';
import { stringify } from 'qs';

// eslint-disable-next-line max-params
export async function apiRequest(endPoint, queryParams = {}, method = 'GET', version = 1, apiToken) {
    const axios = require('axios');

    try {
        const configuratedRequest = getRequest(endPoint, queryParams, method, version, apiToken);
        const response = await axios(...configuratedRequest);

        const json = response.data;

        if (json._errors && json._errors.length > 0) {
            throw new Error(
                json._errors
                    .map(err => err.userFacingMessage || err.message)
                    .join(', '),
            );
        }

        return json;
    } catch (e) {
        console.error(e);
        return null;
    }
}

/** @private */
// eslint-disable-next-line max-params
function getRequest(endPoint, params, method, version, apiToken) {
    let url = `https://mein.toubiz.de/api/v${version}/${endPoint}`;
    let options = {
        method,
        headers: {
            'X-Toubiz-Correlation-Id': correlationId,
            'X-Toubiz-Referrer': location.href,
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': `Bearer ${apiToken}`,
        },
        data: JSON.stringify(params),
    };

    return [ url, options ] = useParametersAsUrlQueryInsteadOfBodyForGetRequests(url, options, method, params);
}

/** @private */
function useParametersAsUrlQueryInsteadOfBodyForGetRequests(url, options, method, params) {
    if (method !== 'GET') {
        return [ url, options ];
    }

    if (options?.body) {
        delete options.body;
    }
    if (options?.headers?.[ 'Content-Type' ]) {
        delete options.headers[ 'Content-Type' ];
    }

    const query = stringify(params, {
        encoder(value, defaultEncoder) {
            if (value === true) {
                return '1';
            } else if (value === false) {
                return '0';
            }

            return defaultEncoder(value);
        },
    });

    return [ `${url}?${query}`, options ];
}