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

import { GET_AIW_TAGLOG_DATA } from '@/graphql/services/aiWorkbench/constants/tagLog';

import { GET_AIW_TAGLOG_DATA_PAYLOAD } from '@/graphql/services/aiWorkbench/types/tagLog/payload/data';

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

const gqlQuery = `
  query ${GET_AIW_TAGLOG_DATA}($payload: ${GET_AIW_TAGLOG_DATA_PAYLOAD}) {
    ${GET_AIW_TAGLOG_DATA}(payload: $payload) {
      hasNext
      hasPrevious
      groups {
        startTime
        endTime
        log {
          created
          startTime
          endTime
          type
          uid
          version
          videoUid
          name
          index
          distributionStatus
          iabCategories {
            data
          }
          clipUrl
          text
          keywords {
            category
            value
            id
            probability
            version
            labelId
            labelName
            color
          }
          joinedKeywords {
            category
            value
          }
        }
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getDataAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);
      const { startTime } = action.payload || {};
      const payload = {
        videoId: video.uid,
        startTime,
        next: 100000,
      };

      const stream$ = gqlRequest({
        query: gqlQuery,
        variables: {
          payload,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const rowData = data[GET_AIW_TAGLOG_DATA]?.groups || [];

          if (!errors?.length) {
            actions.push(
              of(
                setAction({
                  data: rowData,
                  isLoading: false,
                }),
              ),
            );
          }

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

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