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

import { GET_ITEM } from '../../../../../graphql/services/contentOwners/constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '../../../../../graphql/services/contentOwners/types/payload/item';

import { getItemAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  query ${GET_ITEM}($payload: ${PAYLOAD_NAME}) {
    ${GET_ITEM}(payload: $payload) {
      name
      status
      type
      comments
      account_id
      account_name
      account_type
      call_to_action
      play_from_co
      isPublic
      feed_priority
      salesforce_id
    }
  }
`;

const getResponse = ({ data }) => {
  const item = data[GET_ITEM];

  return {
    name: item.name,
    status: item.status,
    type: item.type,
    comments: item.comments,
    account: item.account_id
      ? {
          id: item.account_id,
          value: item.account_id,
          label: item.account_name || 'Empty',
          type: item.account_type,
        }
      : null,
    callToAction: !!item.call_to_action,
    playFromCo: !!item.play_from_co,
    isPublic: item.isPublic,
    feedPriority: item.feed_priority,
    salesforceId: item.salesforce_id,
  };
};

export default (action$) =>
  action$.pipe(
    ofType(getItemAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest(
        {
          query,
          variables: {
            payload: {
              id: action.payload.id,
            },
          },
        },
        {
          showNotificationMessage: false,
        },
      ).pipe(
        switchMap((response) => {
          const actions = [];

          if (response.errors.length) {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: "Can't open for edit",
                }),
              ),
            );

            Router.push('/content-owners');
          } else {
            const data = getResponse(response);

            actions.push(
              of(
                setAction({
                  ...data,
                }),
              ),
            );
          }

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

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