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

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

const queryGQL = `
  mutation AiWorkbenchSetDescriptionQuery(
    $videoId: String!,
    $description: String,
  ) {
    aiWorkbenchSetDescription(
      videoId: $videoId,
      description: $description,
    ) {
      published
      draft
      processing
      description
      descriptions {
        type
        value
      }
    }
  }
`;

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

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
          description: action.payload,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const response = data.aiWorkbenchSetDescription;
          const payload = { isLoading: false };

          if (!errors?.length) {
            payload.description = response.description;
            payload.descriptions = response?.descriptions ?? [];
            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$);
    }),
  );
