import { BulkIndexDocumentsParams } from "elasticsearch";
import { connectES } from "../helpers";
import { initCommonMiddlewares } from "../middlewares";

interface IEvent {
  indexName: string;
  type: string;
  data: any;
}

interface IResult {
  total: number;
  successful: number;
  failed: number;
}

const { ELASTICSEARCH_ENDPOINT, INDEX_PREFIX } = process.env;

async function awsHandler(event: IEvent): Promise<IResult> {
  const { data, indexName, type } = event;

  const connection = connectES(ELASTICSEARCH_ENDPOINT);
  const isConnected = connection.ping({ requestTimeout: 2000 });

  if (!isConnected) {
    throw new Error("Couldn't establish elasticsearch connection");
  }

  const params = createIndexParams(indexName, type, data);
  const response = await connection.bulk(params);

  return parseResponse(response);
}

function parseResponse(response: any): IResult {
  const { errors, items } = response;

  console.log("Receive response: ", JSON.stringify({ errors, items }));

  const result: IResult = {
    total: 0,
    successful: 0,
    failed: 0,
  };

  return items.reduce((result, { index }) => {
    if (index && index._shards) {
      result.total += index._shards.total;
      result.successful += index._shards.successful;
      result.failed += index._shards.failed;
    }
    return result;
  }, result);
}

function createIndexParams(
  indexName: string,
  type: string,
  data: any,
): BulkIndexDocumentsParams {
  const documents = Array.isArray(data) ? data : [data];
  const params = {
    body: [],
    refresh: false,
  };
  documents.forEach((document) => {
    params.body.push({
      index: {
        _index: `${INDEX_PREFIX}_${indexName}`,
        _type: type,
        _id: document.id,
      },
    });
    params.body.push(document);
  });
  return params;
}

export const handler = initCommonMiddlewares(awsHandler);
