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

import { embedCodePopupSelector } from '../selectors';
import { getEmbedCodeAction, getEmbedCodeSuccessAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query getPlaylistEmbedCode(
    $playerId: Int!,
    $playlistId: String,
    $aspectRatio: String
  ) {
    getPlaylistEmbedCode(
      playerId: $playerId,
      playlistId: $playlistId,
      aspectRatio: $aspectRatio
    ) {
      displayEmbedCode
      embedCode
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getEmbedCodeAction.type),
    switchMap(({ payload = {} }) => {
      const embedCodePopup = embedCodePopupSelector(state$.value);

      const variables = {
        playlistId: `${embedCodePopup.playlistId}`,
        playerId: embedCodePopup.player?.value,
        aspectRatio: embedCodePopup.aspectRatio?.label,
        ...payload,
      };

      const stream$ = gqlRequest({ query: queryGQL, variables }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          if (!errors.length) {
            actions = [of(getEmbedCodeSuccessAction(data.getPlaylistEmbedCode?.embedCode))];
          }

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

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