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

export function* createTraiSMSTemplates({ templates, callback }) {
  let errorMsg;
  try {
    const result = yield call(Api.createBulkSMSTemplate, templates);
    if (result?.status?.code && result.status.code >= 400) {
      errorMsg = result.message?.message || result.message;
      throw errorMsg;
    }
    yield put({ type: types.CREATE_TRAI_SMS_TEMPLATE_SUCCESS, data: result.response, statusCode: result.status ? result.status.code : '', errorMsg });

    if (callback) {
      callback(result.response);
    }
  } catch (error) {
    yield put({ type: types.CREATE_TRAI_SMS_TEMPLATE_FAILURE, error, errorMsg });
    if (callback) {
      callback(null, errorMsg);
    }
  }
}

export function* createTraiSMSDuplicates({ payload }) {
  try {
    const result = yield call(Api.checkBulkDuplicates, payload);
    if (
      result?.status?.isError ||
      (result?.status?.code && result.status.code >= 400)
    ) {
      throw result?.status?.message || result?.message;
    }
    yield put({
      type: types.CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_SUCCESS,
      data: result?.response || {},
    });
  } catch (error) {
    yield put({
      type: types.CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_FAILURE,
      error,
    });
  }
}
function* watchCheckDuplicate() {
  yield takeLatest(types.CHECK_TRAI_SMS_DUPLICATE_TEMPLATE_NAME_REQUEST, createTraiSMSDuplicates);
}

function* watchCreateTemplate() {
  yield takeLatest(types.CREATE_TRAI_SMS_TEMPLATE_REQUEST, createTraiSMSTemplates);
}

export default [watchCreateTemplate, watchCheckDuplicate];

export function* v2SmsTraiCreateSagas() {
  yield all([watchCreateTemplate(), watchCheckDuplicate()]);
}