import { call, put, takeLatest, all } from "redux-saga/effects";
import * as Api from "../../services/api";
import {
  ZALO_TEMPLATE_INFO_REQUEST,
  ZALO_TEMPLATE_INFO_SUCCESS,
  ZALO_TEMPLATE_INFO_ERROR,
  ZALO_TEMPLATE_PREVIEW_INFO,
} from "./constants";

export function* getTemplateInfoById({ payload }) {
  const { preview = "", actionCallback } = payload;
  try {
    const res = yield call(Api.getTemplateInfoById, payload);
    if (res?.success) {
      yield put({
        type: preview ? ZALO_TEMPLATE_PREVIEW_INFO : ZALO_TEMPLATE_INFO_SUCCESS,
        result: res?.response || {},
      });
    } else {
      const errorMsg = res?.message || res?.status?.message;
      yield put({
        type: ZALO_TEMPLATE_INFO_ERROR,
        error: errorMsg,
      });
      if (actionCallback) {
        actionCallback(errorMsg);
      }
    }
  } catch (error) {
    yield put({ type: ZALO_TEMPLATE_INFO_ERROR, error });
    if (actionCallback) {
      actionCallback(error);
    }
  }
}

export function* watchForGetTemplateInfoById() {
  yield takeLatest(ZALO_TEMPLATE_INFO_REQUEST, getTemplateInfoById);
}

export default [watchForGetTemplateInfoById];

export function* v2ZaloSagas() {
  yield all([watchForGetTemplateInfoById()]);
}
