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

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

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

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

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

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

          return EMPTY;
        }),
      );

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