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

import { sendFormReportToUserEmailAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation SendFormReportToUserEmail(
    $formId: Int!,
    $bucket: String!,
    $path: String!,
    $startDate: String!,
    $endDate: String!,
  ) {
    sendFormReportToUserEmail(
      formId: $formId,
      bucket: $bucket,
      path: $path,
      startDate: $startDate,
      endDate: $endDate,
    ) {
       status
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(sendFormReportToUserEmailAction.type),
    switchMap((action) => {
      const {
        formId,
        bucketConfig: { bucket, path },
        startDate,
      } = action.payload;

      const stream$ = gqlRequest({
        query,
        variables: {
          formId,
          bucket,
          path,
          startDate: dayjs(startDate).format('YYYY-MM-DD'),
          endDate: dayjs(startDate).add(30, 'days').format('YYYY-MM-DD'),
        },
      }).pipe(switchMap(() => EMPTY));

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