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

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

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

const queryGQL = `
  query exchangeFacebookAuthCode($code: String!) {
    exchangeFacebookAuthCode(code: $code) {
      expiryDate
      accessToken
      userName
      pages {
        id
        title
        token
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(exchangeFacebookAuthCodeAction.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({
                  ...data.exchangeFacebookAuthCode,
                  status: SETTINGS_STATUS_ENABLED,
                  channels: data.exchangeFacebookAuthCode.pages,
                }),
              ),
            );
          }

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

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