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

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

const queryGQL = `
  mutation AiWorkbenchSetHighlightsQuery(
    $videoId: String!,
    $highlights: [AiWorkbenchHighlightInputType],
  ) {
    aiWorkbenchSetHighlights(
      videoId: $videoId,
      highlights: $highlights,
    ) {
      published
      draft
      processing
      highlights {
        id
        start
        end
      }
    }
  }
`;

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

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
          highlights: action.payload.map((highlight) => ({
            ...highlight,
            ...(highlight.id.search('new') === -1 ? { id: highlight.id } : {}),
          })),
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const response = data.aiWorkbenchSetHighlights;
          const payload = { isLoading: false };

          if (!errors?.length) {
            payload.highlights = response?.highlights ?? [];
            payload.published = response.published;
            payload.draft = response.draft;
            payload.processing = response.processing;
            payload.isDirty = true;
          }

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

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