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

import { getKeyListByIdAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query keyListById(
    $id: String
  ) {
    keyListById(
      id: $id
    ) {
      id
      created
      updated
      name
      keys
      count
      status
      updatedBy
      user
      daccountId
      daccountName
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getKeyListByIdAction.type),
    filter(({ payload }) => payload.id),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          id: payload.id,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { name, keys, daccountName, daccountId } = data.keyListById;

            actions.push(
              of(
                setFieldAction({
                  name: payload.isDuplicate ? `Copy_of_${name}` : name,
                  keys: keys?.map((item, index) => ({ id: keys.length - index, name: item })) ?? [],
                  demandAccount: { label: daccountName, value: daccountId },
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );

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