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

type DeleteId = number | number[] | string | string[];
interface IEvent {
  indexName: string;
  type: string;
  id: DeleteId;
}

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

const { ELASTICSEARCH_ENDPOINT, INDEX_PREFIX } = process.env;

async function awsHandler(event: IEvent): Promise<IResult> {
  const { id, 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 = createDeleteParams(indexName, type, id);
  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, { delete: del }) => {
    if (del && del._shards) {
      result.total += del._shards.total;
      result.successful += del._shards.successful;
      result.failed += del._shards.failed;
    }
    return result;
  }, result);
}

function createDeleteParams(
  indexName: string,
  type: string,
  id: DeleteId,
): BulkIndexDocumentsParams {
  const references = Array.isArray(id) ? id : [id];

  const params = {
    body: [],
    refresh: false,
  };

  references.forEach((id) => {
    params.body.push({
      delete: {
        _index: `${INDEX_PREFIX}_${indexName}`,
        _type: type,
        _id: id,
      },
    });
  });
  return params;
}

export const handler = initCommonMiddlewares(awsHandler);
