import { all, takeLatest, call, put } from "@redux-saga/core/effects";
import {
  attemptFetchReview,
  attemptGiveReview,
} from "../../request/reviewRequest";
import {
  REVIEW_GET,
  REVIEW_GIVE,
} from "../actions/review/reviewActionConstants";
import {
  fetchReviewsError,
  fetchReviewsSuccess,
  giveReviewError,
  giveReviewSuccess,
  setReviews,
} from "../actions/review/reviewActions";

function* fetchReviews(payload) {
  try {
    const data = yield call(attemptFetchReview, payload.payload);
    yield put(setReviews([...data.data].reverse()));
    yield put(fetchReviewsSuccess());
  } catch (e) {
    yield put(fetchReviewsError());
    console.log(e);
  }
}

function* giveReview(payload) {
  try {
    yield call(attemptGiveReview, payload.payload.review);
    if (payload.payload.handleApiResponseSuccess) {
      yield call(payload.payload.handleApiResponseSuccess);
    }
    yield put(giveReviewSuccess());
  } catch (e) {
    yield put(giveReviewError());
    console.log(e);
  }
}

export default function* reviewSaga() {
  yield all([
    takeLatest(REVIEW_GET, fetchReviews),
    takeLatest(REVIEW_GIVE, giveReview),
  ]);
}
