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

import { configSelector } from '../../../filterContainer/redux/selectors';
import { configAction } from '../../../filterContainer/redux/slices';
import { accountGetOwnersAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query GetVideoFiltersContentOwnersByAccountQuery(
    $accountId: Int
  ) {
    getVideoFiltersContentOwnersByAccount(
      accountId: $accountId, 
    ) {
      rows {
        id
      }
    }
  }
`;

const getResponse = ({ data: { getVideoFiltersContentOwnersByAccount } }) =>
  getVideoFiltersContentOwnersByAccount.rows.map((co) => co.id);

export default (action$, state$) =>
  action$.pipe(
    ofType(accountGetOwnersAction.type),
    switchMap((action) => {
      const config = configSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          accountId: action.payload,
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            const contentOwners = getResponse(response);

            const filters = {
              ...config,
              account: {
                ...config.account,
                filters: [
                  {
                    ...config.account.filters[0],
                    value: [
                      {
                        ...config.account.filters[0].value[0],
                        owners: contentOwners,
                      },
                    ],
                  },
                ],
              },
            };

            actions.push(
              of(
                configAction({
                  ...filters,
                }),
              ),
            );
          }

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

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