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

import { createSystemTagAction } 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(createSystemTagAction.type),
    switchMap((action) => {
      const { value, category, callbackAfterCreate } = action.payload;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          keywords: [{ lang: 'EN', value }],
          types: ['OWN_CONTENT'],
          status: 'REVIEW',
          source: 'OWN_CONTENT',
          category,
        },
      }).pipe(
        tap(({ data, errors }) => {
          if (!errors.length) {
            const { uid, keywords } = data.createTaxonomyKeyword;
            const createdTag = {
              id: uid,
              label: keywords[0].value,
              value: keywords[0].value,
            };
            callbackAfterCreate(createdTag);
          }

          return EMPTY;
        }),
        switchMap(() => EMPTY),
      );

      return concat(stream$);
    }),
  );
