import * as md5 from "md5";
import { activitiesStats, search } from "../invokers/search";

export default {
  search: async (root, { input }) => {
    const searchResponse = await search.execute(input);

    let statsResponse = {
      items: [],
      queryTime: 0,
    };

    if (searchResponse.items.length) {
      statsResponse = await activitiesStats.execute(
        searchResponse.items.map(({ name, namespace }) => ({
          name,
          namespace,
        })),
      );
    }

    const searchItemsIndex = searchResponse.items.reduce((index, item) => {
      const packageHash = md5((item.namespace || "none") + item.name);
      index[packageHash] = {
        ...item,
        stats: {
          successful: 0,
          failed: 0,
          latestRelease: new Date().toISOString(),
        },
      };
      return index;
    }, {});

    statsResponse.items.forEach((item) => {
      searchItemsIndex[item.packageHash] = {
        ...searchItemsIndex[item.packageHash],
        stats: {
          ...searchItemsIndex[item.packageHash].stats,
          ...item,
        },
      };
    });

    const items = Object.keys(searchItemsIndex).map(
      (packageHash) => searchItemsIndex[packageHash],
    );

    const queryTime = statsResponse.queryTime + searchResponse.queryTime;
    const response = { items, queryTime };

    return response;
  },
};
