import { put, takeEvery, all, call } from 'redux-saga/effects';

import gql from 'graphql-tag';

// Action type
import { StoreAction } from 'store/utils/actions';

import { genericApolloSaga, genericMutation, genericQuery } from 'store/utils/apollo';

import { config, zeus } from 'config/general';

import { deepOmit } from 'store/utils/helper';
import actions from './actions';
import selectors from './selectors';
import * as models from './models';

const { Zeus, $ } = zeus;

export const treatmentOut = values => {
  const output = {
    ...values,
  };

  return deepOmit(output, ['_id', '__typename', 'createdAt', 'updatedAt']);
};

function* list(action: StoreAction) {
  yield call(
    genericQuery({
      objectReturn: '{{camelCase name}}sGetMany',
      search: action?.payload?.data,
      model: models.{{camelCase name}}ListModel,
      actionRes: actions.list.result.action,
    }),
    action,
  );
}

function* detail(action) {
  yield call(
    genericQuery({
      objectReturn: '{{camelCase name}}sGetOne',
      search: {
        id: action?.payload?.id,
      },
      model: models.{{camelCase name}}Model,
      actionRes: actions.detail.result.action,
    }),
    action,
  );
}

/**
 * MUTATIONS
 */

function* add(action: StoreAction) {
  yield call(
    genericMutation({
      objectReturn: '{{camelCase name}}sAddOne',
      model: models.{{camelCase name}}Model,
      actionRes: actions.add.result.action,
    }),
    action,
  );
}

function* update(action: StoreAction) {
  yield call(
    genericMutation({
      objectReturn: '{{camelCase name}}sEditOne',
      model: models.{{camelCase name}}Model,
      search: {
        id: action?.payload?.id,
      },
      actionRes: actions.update.result.action,
    }),
    action,
  );
}

function* delete{{pascalCase name}}(action: StoreAction) {
  yield call(
    genericMutation({
      objectReturn: '{{camelCase name}}sDeleteOne',
      model: models.{{camelCase name}}Model,
      search: {
        id: action?.payload?.id,
      },
      actionRes: actions.delete.result.action,
    }),
    action,
  );
}

function* {{camelCase name}}Watchers() {
  yield all([
    takeEvery(actions.list.request.constant, list),
    takeEvery(actions.detail.request.constant, detail),
    takeEvery(actions.add.request.constant, add),
    takeEvery(actions.update.request.constant, update),
    takeEvery(actions.delete.request.constant, delete{{pascalCase name}}),
  ]);
}

export default function* saga() {
  yield call({{camelCase name}}Watchers);
}
