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

import { TAG_SYSTEM_CATEGORY_CUSTOM, TAG_SYSTEM_CATEGORY_IAB, TAG_SYSTEM_CATEGORY_TEXT } from '../../constants';
import { GET_AIW_TAGLOG_TAG_INFO } from '@/graphql/services/aiWorkbench/constants/tagLog';

import { GET_AIW_TAGLOG_TAG_INFO_PAYLOAD } from '@/graphql/services/aiWorkbench/types/tagLog/payload/tagInfo';

import { getInfoTooltipKey } from '../../helpers';
import { tagInfoSelector } from '../selectors';
import { getTagInfoAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { selectedVideoSelector } from '@/modules/editorial/aiWorkbench/AiWorkbench/redux/selectors';

const TAG_REST_TYPES_DEFAULT_PAYLOAD = 'TAG_REST_TYPES_DEFAULT_PAYLOAD';
const createRequestPayload = (tag) => {
  const mapper = {
    [TAG_SYSTEM_CATEGORY_CUSTOM]: {
      labelId: tag.labelId || tag.id,
      labelValue: tag.value,
    },
    [TAG_SYSTEM_CATEGORY_TEXT]: {
      text: tag.value,
    },
    [TAG_REST_TYPES_DEFAULT_PAYLOAD]: {
      uid: tag.id,
    },
  };

  return mapper[tag.category] || mapper[TAG_REST_TYPES_DEFAULT_PAYLOAD];
};

const gqlQuery = `
  query ${GET_AIW_TAGLOG_TAG_INFO}($payload: ${GET_AIW_TAGLOG_TAG_INFO_PAYLOAD}) {
    ${GET_AIW_TAGLOG_TAG_INFO}(payload: $payload) {
      created
      versions {
        version
        type
        description
      }
      providers {
        provider
        models {
          value
          probability
        }
      }
      editHistory {
        refUserId
        added
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getTagInfoAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);
      const tagInfo = tagInfoSelector(state$.value);
      const { logRowUid = null, tag, context } = action.payload;
      const keywordId = tag.id || tag.value;
      const payload = {
        videoId: video.uid,
        tagId: logRowUid,
        isIab: tag.category === TAG_SYSTEM_CATEGORY_IAB,
        ...createRequestPayload(tag),
      };

      const stream$ = gqlRequest(
        {
          query: gqlQuery,
          variables: {
            payload,
          },
        },
        { showNotificationMessage: false },
      ).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const tagInfoFromApi = data[GET_AIW_TAGLOG_TAG_INFO];
          const key = getInfoTooltipKey(context, keywordId, logRowUid);
          const tagInfoUpdated = {
            ...tagInfo,
            [key]: !errors?.length ? tagInfoFromApi : {},
          };

          actions.push(
            of(
              setAction({
                tagInfo: tagInfoUpdated,
                isLoading: false,
              }),
            ),
          );

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

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