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

import { getPlaylistByIdAction, getPlaylistVideosAction, setPlaylistEntityAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query getPlaylistById($id: Int!) {
    getPlaylistById(id: $id){
      id
      status
      isPrefix
      name
      url
      createdAt
      updatedAt
      createdBy
      updatedBy
      clips
      playerAlias
      widgetName
      pubName
      publisherId
      playerAspectRatio
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPlaylistByIdAction.type),
    switchMap(({ payload }) => {
      const { playlistId } = payload;
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id: playlistId,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const playlist = data.getPlaylistById;

            if (playlist.id) {
              actions.push(
                of(
                  setPlaylistEntityAction({
                    [playlist.id]: playlist,
                  }),
                ),
              );
            }

            if (playlist.clips?.length) {
              actions.push(of(getPlaylistVideosAction(playlist.clips)));
            }
          }

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

      return concat(stream$);
    }),
  );
