import dayjs from 'dayjs';
import durationPlugin from 'dayjs/plugin/duration';
import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { getTimeOption } from '../../helpers';
import { getChartDataAction, getLiveEventByIdAction, getLivePerformanceTotalsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserTimezoneSelector } from '@/modules/@common/user/redux/selectors';

dayjs.extend(durationPlugin);

const queryGQL = `
  query analyticsLiveEventById($id: Int!) {
    analyticsLiveEventById(id: $id) {
      id
      title
      startTime
      endTime
      durationIn
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getLiveEventByIdAction.type),
    switchMap((action) => {
      const timezone = getUserTimezoneSelector(state$.value);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id: action.payload.id,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { analyticsLiveEventById } = data;

            const liveEventSchedulesResult =
              analyticsLiveEventById?.map((schedule) => {
                const duration = dayjs.duration(schedule.endTime - schedule.startTime).as('MINUTES');

                return {
                  ...schedule,
                  label: schedule.title,
                  value: schedule.id,
                  time: getTimeOption(schedule.startTime, schedule.endTime, timezone),
                  duration,
                };
              }) ?? [];

            actions.push(
              of(
                setFieldAction({
                  sessionsOptions: liveEventSchedulesResult,
                  sessions: liveEventSchedulesResult,
                }),
              ),
              of(
                getLivePerformanceTotalsAction({
                  scheduleSessionIds: liveEventSchedulesResult?.map((item) => item.value) ?? [],
                }),
              ),
              of(
                getChartDataAction({
                  scheduleSessionIds: liveEventSchedulesResult?.map((item) => item.value) ?? [],
                }),
              ),
            );
          }

          return concat(...actions);
        }),
      );

      return concat(stream$);
    }),
  );
