import {JitsuElasticsearch, ElasticsearchDestinationConfig} from "./elasticsearch-destination";
import {ConfigValidator, DestinationFunction, ExtensionDescriptor} from "@jitsu/types/extension";

const destination: DestinationFunction = JitsuElasticsearch

const validator: ConfigValidator<ElasticsearchDestinationConfig> = async (config) => {
    ['elasticsearch_domain', 'elasticsearch_port', 'elasticsearch_target', 'elasticsearch_apikey'].forEach(prop => {
        if (config[prop] === undefined) {
            throw new Error(`Required property '${prop}' is absent in config. Present props: ${Object.keys(config)}`);
        }
    })

    var posturl = config.elasticsearch_domain;
    if(typeof config.elasticsearch_port !== "undefined" && config.elasticsearch_port !== ""){
      posturl = posturl + ":" + config.elasticsearch_port
    }
    posturl = posturl + "/" + config.elasticsearch_target + "/_doc/"

    const myHeaders = {
      "Authorization": "ApiKey "+config.elasticsearch_apikey,
      "Content-Type": "application/json",
    }

    var raw = JSON.stringify({
      "jitsu_test": {
        "test": {
          "number_of_replicas": 1
        },
        "test2": {
          "number_of_shards": 1,
        }
      }
    });

    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: raw,
      redirect: 'follow' as RequestRedirect
    };

    let res = await fetch(posturl, requestOptions);

    if (res.status === 201) {
        return {ok: true}
    } else {
        return {ok: false, message: `Response status:${res.status} from url:${posturl}`}
    }
}

const descriptor: ExtensionDescriptor<ElasticsearchDestinationConfig> = {
    id: "jitsu-elasticsearch-destination",
    displayName: "elasticsearch",
    icon: "",
    description: "Jitsu can send events to Elasticsearch API filling as much Elasticsearch Events",
    configurationParameters: [
        {
            id: "anonymous",
            type: "boolean",
            required: false,
            displayName: "Send anonymous data",
            documentation: "Send anonymous data to Elasticsearch if true or all data including user data if false.",
        },
        {
            id: "elasticsearch_domain",
            type: "string",
            required: true,
            displayName: "Elasticsearch server domain including protocol (http(s)://<domain>)",
            documentation: "Url domain",
        },
        {
            id: "elasticsearch_port",
            type: "string",
            required: false,
            displayName: "Elasticsearch server port",
            documentation: "Url port",
        },
        {
            id: "elasticsearch_target",
            type: "string",
            required: true,
            displayName: "Elasticsearch server port",
            documentation: "If the Elasticsearch security features are enabled, you must have the following index privileges for the target data stream, index, or index alias:\n"+
                           "To add or overwrite a document using the PUT /<target>/_doc/<_id> request format, you must have the create, index, or write index privilege.\n"+
                           "To add a document using the POST /<target>/_doc/, PUT /<target>/_create/<_id>, or POST /<target>/_create/<_id> request formats, you must have the create_doc, create, index, or write index privilege.\n"+
                           "To automatically create a data stream or index with an index API request, you must have the auto_configure, create_index, or manage index privilege."
        },
        {
            id: "elasticsearch_apikey",
            type: "string",
            required: true,
            displayName: "Elasticsearch API key",
            documentation: "https://www.elastic.co/guide/en/kibana/master/api-keys.html"
        },

    ],
}

export {descriptor, destination, validator}
