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

import * as selectors from '../selectors';
import { getSharedUsersNameAction, updateStateByParamAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query accessGetSharedUsersName(
    $userIds: [Int],
    $videoId: String
  ) {
    accessGetSharedUsersName(
      userIds: $userIds,
      videoId: $videoId,
    ) {
      records {
        id
        email
        firstName
        lastName
      }  
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getSharedUsersNameAction.type),
    switchMap((action) => {
      const accessUsers = action.payload;
      const videoId = selectors.videoIdSelector(state$.value);

      const variables = {
        userIds: accessUsers.map((u) => parseInt(u.id, 10)),
        videoId,
      };

      const stream$ = gqlRequest({
        query,
        variables,
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const updateAccessUsers = accessUsers.map((accessUser) => {
            const userInfo = data.accessGetSharedUsersName.records.find((info) => +info.id === +accessUser.id);
            if (userInfo) {
              return {
                ...accessUser,
                firstName: userInfo.firstName || '',
                lastName: userInfo.lastName || '',
                email: userInfo.email,
              };
            }
            return accessUser;
          });

          if (!errors.length) {
            actions.push(
              of(
                updateStateByParamAction({
                  accessUsers: updateAccessUsers,
                  isAccessUsersLoading: false,
                }),
              ),
            );
          }

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

      return concat(of(updateStateByParamAction({ isAccessUsersLoading: true })), stream$);
    }),
  );
