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

const gqlQuery = `
  query GetEntities(
    $sortBy: String
    $sortOrder: String
    $page: Int
    $pageSize: Int
    $searchText: String
    $accountId: Int
    $image: String
    $category: String
    $status: String
    $xrayStatus: String
    $searchIn: [String]
  ) {
    getEntities(
      sortBy: $sortBy
      sortOrder: $sortOrder
      page: $page
      image: $image
      pageSize: $pageSize
      searchText: $searchText
      accountId: $accountId
      category: $category
      status: $status
      searchIn: $searchIn
      xrayStatus: $xrayStatus
    ) {
      recordsTotal
      records {
        id
        uid
        refUserId
        thumbnailFileUrl
        value
        category
        status
        score
        source
        types
        playCount
        counterVideos
        updated
        created
        metaData {
          birthDate
          iab
        }
        account {
          id
          name
        }
        keywords {
          lang
          value
          suggestions
        }
      }
    }
  }
`;

export default createEpicGetData({
  gqlQuery,
  triggerActionType: getDataAction.type,
  processBodyRequest: (state) => {
    const account = entitiesSelectors.accountSelector(state);

    const variables = {
      searchText: entitiesSelectors.searchSelector(state),
      page: entitiesSelectors.pageSelector(state),
      pageSize: entitiesSelectors.pageSizeSelector(state),
      sortBy: entitiesSelectors.sortBySelector(state),
      sortOrder: entitiesSelectors.sortOrderSelector(state),
      category: entitiesSelectors.categorySelector(state) || undefined,
      image: entitiesSelectors.imageSelector(state),
      xrayStatus: entitiesSelectors.xrayStatusSelector(state),
      status: entitiesSelectors.tagStatusSelector(state),
    };

    if (account) {
      variables.accountId = account.value;
    }

    return variables;
  },
  processResponse: ({ data: { getEntities } }) => getEntities,
  setTableAction,
});
