import { GET_SELF_SERVE_FEEDS } from '@/graphql/services/feeds/constants';

import { FeedsDataRecordsType } from '../../types';
import { PAYLOAD_NAME } from '@/graphql/services/feeds/types/payload/selfserve/list';

import * as selectors from '../selectors';
import { getDataAction, setTableAction } from '../slices';
import createEpicGetData from '@/modules/@common/Table/redux/epics';

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

export type RequestVariablesType = {
  page: number;
  pageSize: number;
  sortBy: string;
  sortOrder: string;
  searchText?: string;
  searchIn: string[];
  filters?: string[];
  filtersValues?: number[];
};

type DataType = Record<
  string,
  {
    records: FeedsDataRecordsType;
    recordsTotal: number;
    allRecordsCount: number;
  }
>;

const gqlQuery = `
  query ${GET_SELF_SERVE_FEEDS}($payload: ${PAYLOAD_NAME}) {
    ${GET_SELF_SERVE_FEEDS}(payload: $payload) {
      records {
        id
        type
        description
        lang
        status
        schedule_status
        source {
          isConnected
        }
        archived
        updatedBy
        updateDate
      }
      recordsTotal
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state: RootState) => {
    const status = selectors.statusSelector(state);
    const variables: RequestVariablesType = {
      page: selectors.pageSelector(state),
      pageSize: selectors.pageSizeSelector(state),
      sortBy: selectors.sortBySelector(state),
      sortOrder: selectors.sortOrderSelector(state),
      searchText: selectors.searchTextSelector(state),
      searchIn: ['id', 'name', 'description'],
    };

    if (typeof status === 'number') {
      variables.filters = ['status'];
      variables.filtersValues = [status];
    }

    // API for data has updatedDate but for filter request updateDate
    if (variables.sortBy === 'updatedDate') {
      variables.sortBy = 'updateDate';
    }

    return {
      payload: variables,
    };
  },
  processResponse: ({ data }: { data: DataType }) => {
    const feeds = data[GET_SELF_SERVE_FEEDS];

    return {
      records: feeds.records,
      recordsTotal: feeds.recordsTotal,
      allRecordsCount: feeds.recordsTotal,
    };
  },
  setTableAction,
});
