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

export function* createTemplate({template, callback}) {
  let errorMsg;
  try {
    const result = yield call(Api.createMobilePushTemplateV2, template);
    if (result.message) {
      errorMsg = result.message;
      if (result.status && result.status.code >= 400) {
        throw errorMsg;
      }
    }
    if (callback) {
      yield call(callback, result.response);
    }
    yield put({
      type: types.CREATE_TEMPLATE_SUCCESS,
      data: result.response,
      statusCode: result.status ? result.status.code : "",
      errorMsg,
    });
  } catch (error) {
    yield put({ type: types.CREATE_TEMPLATE_FAILURE, error, errorMsg });
  }
}
export function* uploadAsset(action) {
  try {
    const {
      file, assetType, fileParams, index, mobilePushParams = {},
    } = action;
    const uploadParams = {
      file,
      assetType,
      fileParams,
      ...mobilePushParams,
    };
    const result = yield call(Api.uploadFile, uploadParams);

    yield put({
      type: types.UPLOAD_ASSET_SUCCESS,
      data: result.response.asset,
      statusCode: result.status ? result.status.code : "",
      index,
    });
  } catch (error) {
    yield put({ type: types.UPLOAD_ASSET_FAILURE, error });
  }
}

export function* watchCreateTemplate() {
  yield takeLatest(types.CREATE_TEMPLATE_REQUEST, createTemplate);
}
export function* watchUploadAsset() {
  yield takeLatest(types.UPLOAD_ASSET_REQUEST, uploadAsset);
}
export function* watchGetIosCtas() {
  yield takeLatest(types.GET_IOS_CTAS, getIosCtas);
}

export function* editTemplate({ template, callback }) {
  let errorMsg;
  try {
    // Use the same API endpoint as create - backend determines create vs edit based on _id presence
    const result = yield call(Api.createMobilePushTemplateV2, template);
    // Check for error status codes (400+)
    if (result.status.code >= 400) {
      errorMsg = result.message || `HTTP Error ${result.status.code}`;
      throw errorMsg;
    }

    // For edit operations, we need to structure the response similar to create
    // The Templates container expects a templateId field
    const editResponseData = {
      ...result.response,
      templateId: result?.response?.templateId?._id || result?.response?._id || template._id,
    };

    yield put({
      type: types.EDIT_TEMPLATE_SUCCESS,
      data: editResponseData,
      statusCode: result.status ? result.status.code : "",
      errorMsg,
    });

    // Call callback with proper response structure
    if (callback) {
      yield call(callback, editResponseData);
    }
  } catch (error) {
    yield put({ type: types.EDIT_TEMPLATE_FAILURE, error, errorMsg });
  }
}

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

export function* getIosCtas(licenseCode) {
  try {
    const result = yield call(Api.getIosCtas, licenseCode);
    yield put({
      type: types.GET_IOS_CTAS_SUCCESS,
      data: result.response.metaEntities.data,
      statusCode: result.status ? result.status.code : "",
    });
  } catch (error) {
    yield put({ type: types.GET_IOS_CTAS_FAILURE, error });
  }
}

export function* getMobilepushTemplatesList(params) {
  try {
    const result = yield call(Api.getAllTemplates, {
      channel: params.channel,
      queryParams: params.queryParams,
    });
    yield put({
      type: types.GET_MOBILEPUSH_TEMPLATES_LIST_SUCCESS,
      data: result.response.templates,
      templateData: result.response.mapped,
    });
  } catch (error) {
    yield put({ type: types.GET_MOBILEPUSH_TEMPLATES_LIST_FAILURE, error });
  }
}

export function* fetchWeCrmAccounts(action) {
  try {
    const result = yield call(Api.fetchWeCrmAccounts, action.source);
    yield put({
      type: types.GET_WECRM_ACCOUNTS_SUCCESS,
      data: result.response,
    });
  } catch (error) {
    yield put({
      type: types.GET_WECRM_ACCOUNTS_FAILURE,
      data: error,
    });
  }
}

export function* watchFetchWeCrmAccounts() {
  yield takeLatest(types.GET_WECRM_ACCOUNTS_REQUEST, fetchWeCrmAccounts);
}

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

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

export function* watchMobilepushTemplatesList() {
  yield takeLatest(
    types.GET_MOBILEPUSH_TEMPLATES_LIST_REQUEST,
    getMobilepushTemplatesList
  );
}

export default [
  watchEditTemplate,
  watchCreateTemplate,
  watchGetTemplateDetails,
  watchFetchWeCrmAccounts,
  watchMobilepushTemplatesList,
  watchUploadAsset,
  watchGetIosCtas,
];

export function* v2MobilePushSagas() {
  yield all([
    watchCreateTemplate(),
    watchEditTemplate(),
    watchGetTemplateDetails(),
    watchFetchWeCrmAccounts(),
    watchMobilepushTemplatesList(),
    watchUploadAsset(),
    watchGetIosCtas(),
  ]);
}
