import Router from 'next/router';
import type { Action } from 'redux';
import { type Epic } from 'redux-observable';
import { concat, of } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

import { GET_FEED_ITEM } from '@/graphql/services/feeds/constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/feeds/types/payload/feedItem';
import type { FeedType } from '@/modules/feeds/Editor/types';

import { getItemAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import type { RootState } from '@/modules/@common/store/store';

type PayloadType = {
  id: number;
};

type ResponseType<T extends string, Entity> = {
  data: {
    [key in T]: Entity;
  };
  errors: unknown[];
};

const query = `
  query ${GET_FEED_ITEM}($payload: ${PAYLOAD_NAME}) {
    ${GET_FEED_ITEM}(payload: $payload) {
      id
      type
      name
      description
      status
      source {
        isConnected
        importParticipantsNames
      }
      account {
        id
        name
      }
      lang
      accessLevel
      accessAllPublishers
      accessPublishers {
        id
        name
      }
      accessVideoOwner {
        id
        name
      }
      url
      user
      password
      isUseForDownload
      authMethod
      
      scheduleStatus
      scheduleType
      scheduleValue
      scheduleFrequency
      
      feedPriority
      priorityVerification
      
      iabCategories
      defaultTimezone
      defaultTimezoneEnabled
      
      isEvergreenFeed
      isRestricted
      keywords
      parseKeywordsToLabels
      maxDuration
      importPlot
      fileSelection
      resolution
      resolutionValue
      minResolutionValue
      bitrate
      minBitrate
      videoFileType
      importCCFromMrssFile
      createClip
      skipTaggingForLongClips
      maxDurationForTagging
      immediateAvailability
      processVideoVersions
      versionAttributeName
      maxStories
      videoDuration
      aspectRatio
      fit
      jsRendering
      speechToTextProvider
      loadFromLastDays
      discardLongClips
      fillLandingPage
      videoMaxZoom
      
      contentOwnerIsPublic
      
      youtubeContentType
      youTubeChannelId
      youTubeLoadFromDate
      contentType
      importShortsThumbnail
      
      automationScript
      platformModels {
        config
        enabled
        model
        platform
      }
    }
  }
`;

const getResponse = (data: FeedType) => data;

const getAccountOptionsEpic: Epic<Action, Action, RootState> = (action$) =>
  action$.pipe(
    filter((action): action is ReturnType<typeof getItemAction> => action.type === getItemAction.type),
    switchMap((action) => {
      const payload: PayloadType = {
        id: action.payload.id,
      };

      return gqlRequest({
        query,
        variables: { payload },
      }).pipe(
        switchMap((response: ResponseType<typeof GET_FEED_ITEM, FeedType>) => {
          const actions = [];

          if (response.errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: "Can't open for edit",
                }),
              ),
            );

            Router.push('/feeds');
          } else {
            const feedData = getResponse(response.data[GET_FEED_ITEM]);
            actions.push(
              of(
                setAction({
                  ...feedData,
                }),
              ),
            );
          }

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

export default getAccountOptionsEpic;
