/*!
 * Copyright (c) what3words http://what3words.com
 */
import { fetchTransport } from "@what3words/api";
import { isKey } from "./utils";
const UTILISATION_ENABLED_HOSTS = [".*\\.w3w\\.io", ".*\\.what3words\\.com"];
export var SessionType;
(function (SessionType) {
    SessionType["Started"] = "POST";
    SessionType["Updated"] = "PATCH";
})(SessionType || (SessionType = {}));
const isUtilisationEnabledHost = (host) => new RegExp(UTILISATION_ENABLED_HOSTS.join("|")).test(host);
class Utilisation {
    constructor() {
        this.host = "https://utilisation-api.what3words.com";
    }
    /**
     * Sets the API Key
     * @param apiKey W3W API key
     */
    setApiKey(apiKey) {
        this.apiKey = apiKey;
    }
    /**
     * Allows overriding of utilisation api host (i.e: preprod, dev etc)
     * @param host utilisation api host
     */
    setHost(host) {
        this.host = host;
    }
    async send(session) {
        const { key, baseUrl, headers, data, transport = fetchTransport(), type, } = session;
        const apiKey = key || this.apiKey;
        if (!apiKey || !isUtilisationEnabledHost(baseUrl)) {
            return false;
        }
        const request = {
            method: type,
            host: `${this.host.replace(/\/$/, "")}`,
            url: "/autosuggest-session",
            query: { key: apiKey },
            headers: Object.assign({ "Content-Type": "application/json" }, [
                "Origin",
                "User-Agent",
                "X-W3W-Wrapper",
                "X-W3W-AS-Component",
                "X-Correlation-ID",
                "X-W3W-Plugin",
                "X-API-Key",
            ]
                .filter((key) => isKey(headers, key))
                .reduce((acc, key) => {
                if (headers[key]) {
                    acc[key] = headers[key];
                }
                return acc;
            }, {})),
            body: data,
        };
        return transport(request)
            .then((response) => response.status >= 200 && response.status < 300)
            .catch((_err) => false);
    }
}
export default new Utilisation();
