// Import live grouper types
import { StudentGroupAssignment, GrouperAlgoSettings } from 'dce-live-grouper';

// Import types
import CheckInUIProps from '../../../types/CheckInUIProps';
import CreateEventBody from '../../../shared/types/CreateEventBody';
import MMDDYY from '../../../shared/types/MMDDYY';
import Occurrence from '../../../shared/types/Occurrence';
import OccurrenceGrouperInfo from '../../../shared/types/OccurrenceGrouperInfo';

// Import helpers
import toStringMMDDYY from '../../../shared/helpers/toStringMMDDYY';

// Import constants
import TTM_PATH_PREFIX from '../../../shared/constants/TTM_PATH_PREFIX';

/**
 * Function for calling the backend to create EventStateData for the occurrence.
 * @author Benedikt Arnarsson
 */
const postEventForOccurrence = async (
  opts: {
    checkInProps: CheckInUIProps,
    occurrenceDate: MMDDYY,
    occurrenceGrouperInfo: OccurrenceGrouperInfo,
    preAssignments: StudentGroupAssignment[],
    grouperAlgoSettings: GrouperAlgoSettings,
  },
): Promise<void> => {
  const {
    checkInProps,
    occurrenceDate,
    occurrenceGrouperInfo,
    preAssignments,
    grouperAlgoSettings,
  } = opts;

  const {
    courseId,
    ihid,
    visitServerEndpoint,
  } = checkInProps;

  const formattedDate = toStringMMDDYY(occurrenceDate);

  const eventId = `${ihid}-O${formattedDate}`;

  const { seriesId } = occurrenceGrouperInfo;

  // Create occurrence
  const occ: Occurrence = {
    courseId,
    ihid,
    ...occurrenceDate,
    ...occurrenceGrouperInfo,
  };

  await visitServerEndpoint({
    path: `${TTM_PATH_PREFIX}/occurrence`,
    method: 'POST',
    params: {
      occurrence: JSON.stringify(occ),
    },
  });

  // Create event
  const createEventBody: CreateEventBody = {
    courseId,
    eventId,
    preAssignments,
    ...grouperAlgoSettings,
    metadata: {
      seriesId,
    },
  };

  await visitServerEndpoint({
    path: `${TTM_PATH_PREFIX}/grouper/event`,
    method: 'POST',
    params: {
      createEventBody: JSON.stringify(createEventBody),
    },
  });
};

export default postEventForOccurrence;
