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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import createCustomReportRequestBody from '../../helpers/createCustomReportRequestBody';
import { setFieldAction, updateCustomReportAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation UpdateCustomReport(
    $id: Int!,
    $name: String,
    $scheduled: Boolean,
    $scheduleType: String,
    $recipients: [String],
    $scheduleValue: AnalyticsCustomReportScheduleValueInputType,
    $period: String,
    $periodCustomStartDate: String,
    $periodCustomEndDate: String,
    $dimensions: [AnalyticsCustomReportDimensionInputType],
    $filters: [AnalyticsCustomReportFilterInputType],
    $metrics: [AnalyticsCustomReportMetricInputType]
  ) {
    updateCustomReport(
      id: $id,
      name: $name,
      scheduled: $scheduled,
      scheduleType: $scheduleType,
      recipients: $recipients,
      scheduleValue: $scheduleValue,
      period: $period,
      periodCustomStartDate: $periodCustomStartDate,
      periodCustomEndDate: $periodCustomEndDate,
      dimensions: $dimensions,
      filters: $filters,
      metrics: $metrics
    ) {
       id
       name
       scheduled
       scheduleType
       scheduleValue {
        dayInWeek
        dayInMonth
        time
       }
       period
       periodCustomStartDate
       periodCustomEndDate
       lastDelivery
       nextDelivery
       updatedBy
       createdBy
       updatedAt
       createdAt
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateCustomReportAction.type),
    filter(({ payload }) => payload.id),
    switchMap(({ payload }) => {
      const state = state$.value;
      const body = createCustomReportRequestBody(state);

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

          if (!errors.length) {
            actions = [
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Report saved',
                }),
              ),
            ];
          }

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

      return concat(of(setFieldAction({ isLoading: true })), stream$, of(setFieldAction({ isLoading: false })));
    }),
  );
