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

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { attachIdToChapters } from '../../helpers';
import { setAction, setChaptersAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation AiWorkbenchSetChaptersQuery(
    $videoId: String!,
    $chapters: [AiWorkbenchChapterInputType],
  ) {
    aiWorkbenchSetChapters(
      videoId: $videoId,
      chapters: $chapters,
    ) {
      published
      draft
      processing
      chapters {
        time
        name
        description
      }
    }
  }
`;

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

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
          chapters: action.payload.sort((a, b) => a.time - b.time),
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const response = data.aiWorkbenchSetChapters;
          const payload = { isLoading: false };

          if (!errors?.length) {
            payload.chapters = attachIdToChapters(response?.chapters ?? []);
            payload.published = response.published;
            payload.draft = response.draft;
            payload.processing = response.processing;
            payload.editableId = null;
            payload.createId = null;
            payload.isDirty = true;
          }

          return concat(of(setAction(payload)));
        }),
      );

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