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

import { downloadAction, setAction } from '../slices';
import { getFileName } from '@/modules/@common/helpers/format';
import { getToken } from '@/modules/@common/token/helpers';
import { selectedVideoSelector } from '@/modules/editorial/aiWorkbench/AiWorkbench/redux/selectors';

export default (action$, state$) =>
  action$.pipe(
    ofType(downloadAction.type),
    switchMap((action) => {
      const { name, uid } = selectedVideoSelector(state$.value);
      const apiSuffix = action.payload;

      const fileName = getFileName(`${name.replace(/[^A-Za-z0-9_]/g, '-')}-${apiSuffix}`, 'xlsx');

      const request = () =>
        ajax({
          method: 'POST',
          url: `/api/export/${apiSuffix}`,
          headers: {
            Authorization: getToken(),
          },
          body: {
            videoId: uid,
            fromEditorial: true,
          },
          responseType: 'blob',
        });

      const stream$ = defer(() => request()).pipe(
        switchMap(({ response }) => {
          const urlObject = window.URL.createObjectURL(new Blob([response]));
          const link = document.createElement('a');

          link.href = urlObject;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();

          return of(setAction({ isLoading: false }));
        }),
      );

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