const { URL } = require('url');
const fetch = require('./fetch');
const setQuery = require('./setQuery');
const patchFetchUrl = require('./patchFetchUrl');

class APIClient {
    constructor(req, baseUrl, headers) {
        this.req = req;
        this.baseUrl = baseUrl;
        this.headers = headers;
    }
    send(method, path, customOptions = {}) {
        let url = new URL(`${this.baseUrl}${path}`);
        let options = { method, ...customOptions };

        if (!options.headers) {
            options.headers = this.headers;
        }

        url = setQuery(url, options.query);
        url = patchFetchUrl(this.req, url); // ui tests

        delete options.query;

        return fetch(url.href, options);
    }
}

module.exports = APIClient;
