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

import { TYPE_ERROR, TYPE_WARNING } from '@/modules/@common/notify/constants';

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { generateByAiAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { monitoringStartAction } from '@/modules/editorial/editorialSearch/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  mutation AiWorkbenchGenerateChaptersByAiQuery(
    $videoId: String!,
    $notifyByEmail: Boolean!
  ) {
    aiWorkbenchGenerateChaptersByAi(
      videoId: $videoId,
      notifyByEmail: $notifyByEmail,
    )
  }
`;

const ERROR_MODEL_IS_DISABLE = 11101;
const ERROR_MODEL_DOESNT_SUPPORT_LANG = 11102;
const ERROR_MODEL_UPLOADED_CC_AUTO = 11201;
const ERROR_MODEL_DEFAULT = 11200;

const ERRORS = {
  [ERROR_MODEL_IS_DISABLE]:
    'Chapters cannot be generated for this video. Please contact your Customer Success Manager (EO1).',
  [ERROR_MODEL_DOESNT_SUPPORT_LANG]:
    'Chapters cannot be generated for this video due to the video language is not supported. Please contact your Customer Success Manager (E02).',
  [ERROR_MODEL_UPLOADED_CC_AUTO]:
    'Chapters cannot be generated for this video since it has manually uploaded closed captions rather than automatically generated ones.',
  [ERROR_MODEL_DEFAULT]: 'Chapters cannot be generated for this video.',
};

export default (action$, state$) =>
  action$.pipe(
    ofType(generateByAiAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);

      const stream$ = gqlRequest(
        {
          query: queryGQL,
          variables: {
            videoId: video.uid,
            notifyByEmail: action.payload,
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap(({ errors }) => {
          const actions = [of(setAction({ isLoading: false }))];

          if (!errors?.length) {
            actions.push(of(monitoringStartAction()));
            actions.push(of(setAction({ processing: true })));
          } else {
            actions.push(
              of(
                showNotificationAction({
                  type: ERRORS[errors[0]?.response?.code] ? TYPE_WARNING : TYPE_ERROR,
                  message: ERRORS[errors[0]?.response?.code] || ERRORS[ERROR_MODEL_DEFAULT],
                }),
              ),
            );
          }

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

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