// Import dce-reactkit
import { genRouteHandler, ParamType } from '../../../../dce-reactkit';

// Import collections
import { getOccurrenceCollection } from '../../../initCollections';

// Import types
import Router from '../../../types/Router';

// Import shared types
import Occurrence from '../../../shared/types/Occurrence';

/**
 * Endpoint for retrieving the list of series corresponding to the ihid.
 * Returns a list of occurrence IDs.
 * @author Benedikt Arnarsson
 * @param router the router which we are adding this endpoint to.
 */
const addGetSeriesListRoute = (
  router: Router,
) => {
  router.get(
    '/series-list',
    genRouteHandler({
      paramTypes: {
        courseId: ParamType.Int,
        ihid: ParamType.String,
      },
      handler: async ({ params }): Promise<Occurrence[]> => {
        const {
          courseId,
          ihid,
        } = params;
        const occurrenceCollection = getOccurrenceCollection();
        const seriesDocList = await occurrenceCollection.find({
          courseId,
          ihid,
        });

        const seriesList = seriesDocList
          .filter((doc) => {
            // Only want those that have groups enabled
            return doc.grouperEnabled;
          })
          .map((doc) => {
            // Will just be sending the occurrence, no ID
            const {
              id,
              ...occ
            } = doc;
            return occ;
          });

        return seriesList;
      },
    }),
  );
};

export default addGetSeriesListRoute;
