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

const EMPTY_ROWS_NUMBER = 6;

const gqlQuery = `query GetVideoVersions($videoId: String, $site: [String]) {
  getVideoVersions(
    videoId: $videoId
    site: $site
  ) {
    data {
      videoCreationDate
      refVideoVersion
      notes
      videoVersion
    }
    totalCount
  }
}`;

const createEmptyRows = (rowsNumber) =>
  Array.from({ length: rowsNumber }, () => ({
    id: '',
    videoCreationDate: '',
    refVideoVersion: '',
    notes: '',
  }));

export default tableCreateEpicGetData({
  gqlQuery,
  triggerActionType: getTableDataAction.type,
  processBodyRequest: (state, payload) => ({
    videoId: payload.videoId,
    site: payload.site,
    sortBy: selectors.sortBySelector(state),
    sortOrder: selectors.sortOrderSelector(state),
    page: selectors.pageSelector(state),
    pageSize: selectors.pageSizeSelector(state),
  }),
  processResponse: ({ data: { getVideoVersions } }) => {
    const rows = getVideoVersions.data;

    const addEmptyRowsIfNeeds = () => {
      const emptyRowsToAdd = EMPTY_ROWS_NUMBER - rows.length;

      if (emptyRowsToAdd) {
        return rows.concat(createEmptyRows(emptyRowsToAdd));
      }

      return emptyRowsToAdd < 0 ? rows.concat(createEmptyRows(emptyRowsToAdd)) : rows;
    };

    return {
      records: addEmptyRowsIfNeeds(),
      recordsTotal: getVideoVersions.totalCount,
    };
  },
  setTableAction,
});
