import { all, call, put, takeLatest } from "redux-saga/effects";
import {
  getAllAds,
  getAdDetailsById,
  getAllArchiveAds,
  getAllFilteredAds,
  createNewAd,
} from "../../request/adsRequest";
import {
  setAds,
  setAdsError,
  setFilteredAds,
  setFilteredAdsError,
} from "../actions/ads/adsAction";
import { setAd, setAdError } from "../actions/ad/adActions";
import {
  setArchiveAds,
  setArchiveAdsError,
} from "../actions/archiveAds/archiveAdsActions";
import { FETCH_ADS_REQ } from "../actions/ads/adsActionConstants";
import { FETCH_FILTERED_ADS_REQ } from "../actions/ads/adsActionConstants";
import { FETCH_AD_REQ } from "../actions/ad/adActionConstants";
import { FETCH_ARCHIVE_ADS_REQ } from "../actions/archiveAds/archiveAdsActionConstants";
import { CREATE_AD_REQ } from "../actions/createAd/createAdActionConstants";
import {
  setCreateAd,
  setCreateAdError,
} from "../actions/createAd/createAdActions";

export function* getAds() {
  try {
    const result = yield call(getAllAds);
    yield put(setAds(result.data));
  } catch (error) {
    yield put(setAdsError(error));
  }
}

export function* getFilteredAds({ payload }) {
  try {
    const result = yield call(getAllFilteredAds, payload);
    yield put(setFilteredAds(result.data));
  } catch (error) {
    yield put(setFilteredAdsError(error));
  }
}

export function* getAd({ payload }) {
  try {
    const result = yield call(getAdDetailsById, payload.id);
    yield put(setAd(result.data));
  } catch (error) {
    yield put(setAdError(error));
  }
}

export function* getArchiveAds() {
  try {
    const result = yield call(getAllArchiveAds);
    yield put(setArchiveAds(result.data));
  } catch (error) {
    yield put(setArchiveAdsError(error));
  }
}

export function* createAd({ payload }) {
  try {
    const result = yield call(createNewAd, payload);
    const ad = result.data;
    yield put(setCreateAd(ad));
  } catch (error) {
    yield put(setCreateAdError(error));
  }
}

export default function* adsSaga() {
  yield all([
    takeLatest(FETCH_ADS_REQ, getAds),
    takeLatest(FETCH_FILTERED_ADS_REQ, getFilteredAds),
    takeLatest(FETCH_AD_REQ, getAd),
    takeLatest(FETCH_ARCHIVE_ADS_REQ, getArchiveAds),
    takeLatest(CREATE_AD_REQ, createAd),
  ]);
}
