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

import { SETTINGS_STATUS_ENABLED } from '../../constants';

import { exchangeGoogleAuthCodeAction, updateDestinationFormAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query exchangeGoogleAuthCode($code: String!) {
    exchangeGoogleAuthCode(code: $code) {
      expiryDate
      accessToken
      refreshToken
      userName
      channels {
        id
        title
      }
      playlists {
        id
        title
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(exchangeGoogleAuthCodeAction.type),
    switchMap((action) => {
      const { code } = action.payload;

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

          if (!errors.length) {
            actions.push(
              of(
                updateDestinationFormAction({
                  status: SETTINGS_STATUS_ENABLED,
                  ...data.exchangeGoogleAuthCode,
                }),
              ),
            );
          }

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

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