import {
  call, put, takeLatest, all,
} from 'redux-saga/effects';
import * as Api from '../../../services/api';
import * as types from './constants';

// Individual exports for testing
export function* editTemplate(template) {
  let errorMsg;
  try {
    const result = yield call(Api.editTemplate, template);
    // const sidebar = result.response.sidebar;
    if (result?.message || result?.status?.code === 500) {
      errorMsg = result.message;
    }

    yield put({
      type: types.EDIT_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '', errorMsg
    });
    yield template.onUpdateTemplateComplete(result.response, errorMsg);
  } catch (error) {
    yield put({ type: types.EDIT_TEMPLATE_FAILURE, error, errorMsg });
  }
}

export function* getTemplateDetails(id) {
  try {
    const result = yield call(Api.getTemplateDetails, id);
    // const sidebar = result.response.sidebar;
    yield put({ type: types.GET_TEMPLATE_DETAILS_SUCCESS, data: result.response });
  } catch (error) {
    yield put({ type: types.GET_TEMPLATE_DETAILS_FAILURE, error });
  }
}


function* watchEditTemplate() {
  yield takeLatest(types.EDIT_TEMPLATE_REQUEST, editTemplate);
}

function* watchGetTemplateDetails() {
  yield takeLatest(types.GET_TEMPLATE_DETAILS_REQUEST, getTemplateDetails);
}

// All sagas to be loaded
export default [
  watchEditTemplate, watchGetTemplateDetails,
];

export function* v2SmsEditSagas() {
  yield all([
    watchEditTemplate(),
    watchGetTemplateDetails(),
  ]);
}
