import { ofType } from 'redux-observable';
import { concat, of } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

import getStateFromCustomReportRequestBody from '../../helpers/getStateFromCustomReportRequestBody';
import { getCustomReportByIdAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getPublisherIdsSelector, getUserEmailSelector } from '@/modules/@common/user/redux/selectors';

const query = `
  query customReportById(
    $id: Int!
  ) {
    customReportById(
      id: $id
    ) {
      id
      name
      scheduled
      scheduleType
      scheduleValue {
        dayInWeek
        dayInMonth
        time
      }
      recipients
      period
      periodCustomStartDate
      periodCustomEndDate
      lastDelivery
      nextDelivery
      updatedBy
      createdBy
      updatedAt
      createdAt
      dimensions {
        id
        customReportId
        name
        value
        order
      }
      filters {
        id
        customReportId
        name
        label
        value
        action
      }
      metrics {
        id
        customReportId
        name
        value
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getCustomReportByIdAction.type),
    filter(({ payload }) => payload.id),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          id: payload.id,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          const userEmail = getUserEmailSelector(state$.value);
          const userPublisherIds = getPublisherIdsSelector(state$.value);

          if (!errors.length) {
            actions.push(
              of(
                setFieldAction(
                  getStateFromCustomReportRequestBody({
                    body: data.customReportById,
                    isDuplicate: payload.isDuplicate,
                    userEmail,
                    userPublisherIds,
                  }),
                ),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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