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

interface IEvent {
  indexName: string;
  type?: string;
  body: any;
}

interface IResultItem {
  id: string;
  item: any;
  _info: { type: string; index: string };
}

interface IResult {
  items: IResultItem[];
  aggregations: any;
  _info: { took: number };
}

const { ELASTICSEARCH_ENDPOINT, INDEX_PREFIX } = process.env;

async function awsHandler(event: IEvent): Promise<IResult> {
  const { body, 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 response = await connection.search({
    index: parseIndexName(indexName),
    type: type || undefined,
    body,
  });

  console.log("Receive response: ", JSON.stringify(response, null, 4));

  const {
    took,
    aggregations = {},
    hits: { hits },
  } = response;

  const items = hits.map((hit) => {
    return {
      id: hit._id,
      item: hit._source,
      _info: {
        type: hit._type,
        index: hit._index,
      },
    } as IResultItem;
  });

  return { items, aggregations, _info: { took } };
}

function parseIndexName(indexName: string) {
  return indexName
    .split(",")
    .map((idn: string) => `${INDEX_PREFIX}_${idn.trim()}`);
}

export const handler = initCommonMiddlewares(awsHandler);
