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

import { createTaxonomyKeywordAction, isLoadingKeywordsAction, updateVideoAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation createTaxonomyKeyword(
    $category: String!,
    $status: String,
    $source: String,
    $types: [String],
    $keywords: [TaxonomyKeywordInputType]) {
    createTaxonomyKeyword(
      category: $category,
      status: $status,
      source: $source,
      types: $types,
      keywords: $keywords
      ) {
      uid,
      category,
      status,
      source,
      types,
      keywords {
        lang
        value
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(createTaxonomyKeywordAction.type),
    switchMap((action) => {
      const {
        payload: { value, category, video },
      } = action;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          keywords: [{ lang: 'EN', value }],
          types: ['OWN_CONTENT'],
          status: 'REVIEW',
          source: 'OWN_CONTENT',
          category,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const prevKeywords = video?.keywords ?? [];

            actions.push(
              of(
                updateVideoAction({
                  keywords: [
                    ...prevKeywords,
                    {
                      category,
                      value,
                      id: data.createTaxonomyKeyword.uid,
                      version: 'MANUAL_V4',
                    },
                  ],
                }),
              ),
            );
          }

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

      return concat(of(isLoadingKeywordsAction(true)), stream$, of(isLoadingKeywordsAction(false)));
    }),
  );
