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

import { canShowVideoContentOwnerName } from '../../helpers';
import { getOwnersOptionsAction, ownersOptionsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserPermissionsSelector } from '@/modules/@common/user/redux/selectors';

const FEED_TYPES = [
  'MRSS',
  'CSV',
  'YOUTUBE',
  'S3',
  'INSTAGRAM',
  'RSS',
  'VIDEO_API',
  'STORY_API',
  'LIVE',
  'VIMEO',
  'MANUAL',
  'SITEMAP',
  'ZOOM',
];

const query = `
  query getFeedSources(
    $feedTypeFilter: [String],
    $pageSize: Int,
    $searchText: String,
    $isContentOwnerName: Boolean
    ) {
      getFeedSources(
        feedTypeFilter: $feedTypeFilter,
        pageSize: $pageSize,
        searchText: $searchText
        isContentOwnerName: $isContentOwnerName
      ) {
        records {
          id
          name
          display_name
          contentOwnerId
          contentOwnerName
          schedule_status
          status
          contentOwner {
            name
          }
        }
      }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getOwnersOptionsAction.type),
    switchMap((action) => {
      const userPermissions = getUserPermissionsSelector(state$.value);
      const variables = {
        feedTypeFilter: FEED_TYPES.filter((type) => !['RSS', 'STORY_API', 'SITEMAP'].includes(type)),
        pageSize: 100,
      };

      if (action.payload) {
        variables.searchText = action.payload;
      }

      variables.isContentOwnerName = canShowVideoContentOwnerName(userPermissions);

      const getResponse = ({ data: { getFeedSources } }) =>
        getFeedSources.records.map((record) => {
          let label = record.display_name || record.name;

          if (canShowVideoContentOwnerName(userPermissions)) {
            label += `/${record?.contentOwner?.name ?? 'Empty'}`;
          }

          return {
            ...record,
            label,
            value: record.id,
          };
        });

      const stream$ = gqlRequest({
        query,
        variables,
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(of(ownersOptionsAction(getResponse(response))));
          }

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

      return concat(of(ownersOptionsAction(null)), stream$);
    }),
  );
