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

import { setFieldAction, uploadBannerAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation UploadImage(
    $picture: String,
    $fileName: String,
  ) {
    uploadFormBanner(
      picture: $picture
      fileName: $fileName 
    ) {
       url
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(uploadBannerAction.type),
    switchMap((action) => {
      const { image, file, fileName } = action.payload;

      const stream$ = gqlRequest({
        query,
        variables: {
          picture: file,
          fileName,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            const { url: banner } = response.data.uploadFormBanner;
            const [logo] = image;

            return of(
              setFieldAction({
                image: [logo, banner],
              }),
            );
          }

          return EMPTY;
        }),
      );

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